I would like to use sets like they are implemented in MDN with typescript. I have the latest typescript installed in my package:
"typescript": "^5.4.5"
and in my tsconfig I have:
"lib": ["dom", "es2022"],
When I write
const set1:Set<number> = new Set([1,2])
const set2:Set<number> = new Set([1,2,3])
set1.isSubsetOf(set2)
I get
Property 'isSubsetOf' does not exist on type 'Set<number>'.ts(2339)
I tried writing my own interface:
interface Set<T> {
add(value: T): this;
clear(): void;
delete(value: T): boolean;
forEach(
callbackfn: (value: T, value2: T, set: Set<T>) => void,
thisArg?: any
): void;
has(value: T): boolean;
intersection(value: Set<T>): this;
isSubsetOf(value: Set<T>): this;
readonly size: number;
}
and this works when I have this definition in the same file. But as soon as I import this definition from another file I have the same error as before. Can I overwrite the default definition for Sets in Typescript?
tsconfig:
{
"include": ["./src/**/*"],
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
"lib": ["dom", "es2022"],
"jsx": "react-jsx"
}
}
packacke.json:
{
"name": "react-typescript",
"version": "1.0.0",
"description": "React and TypeScript example starter project",
"keywords": [
"typescript",
"react",
"starter"
],
"main": "src/index.tsx",
"dependencies": {
"loader-utils": "3.2.1",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-scripts": "5.0.1"
},
"devDependencies": {
"@types/react": "18.3.3",
"@types/react-dom": "18.3.0",
"typescript": "^5.4.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
Those new Set related features are currently an ECMAScript standard in stage 3 and will be shipped soon in all major browsers.
Hence, TypeScript just recently added these types: https://github.com/microsoft/TypeScript/issues/57228
Those will be released in the next release as part of version 5.5.0. But you need to set the "target" in your TypeScript compiler options to "esnext" in order to use these new types.
See Playground Link.
As pointed out in the comment you can also in the meanwhile create a .d.ts file defining the new type already globally. E.g. create a set.d.ts file (make sure your TS config finds it) and put the following content in it:
declare global {
interface Set<T> {
isSubsetOf<T>(other: ReadonlySet<unknown>): boolean
}
}
// this empty export is important to make it work
export {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With