我想使用sets,就像它们在 MDN 中通过 typescript 实现一样。 我的包中安装了最新的打字稿:
"typescript": "^5.4.5"
在我的 tsconfig 中我有:
"lib": ["dom", "es2022"],
当我写作时
const set1:Set<number> = new Set([1,2])
const set2:Set<number> = new Set([1,2,3])
set1.isSubsetOf(set2)
我明白了
Property 'isSubsetOf' does not exist on type 'Set<number>'.ts(2339)
我尝试编写自己的界面:
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;
}
当我在同一个文件中有这个定义时,这才有效。但是,一旦我从另一个文件导入这个定义,我就会遇到与以前相同的错误。我可以覆盖 Typescript 中 Sets 的默认定义吗?
ts配置:
{
"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"
]
}
这些新的
Set
相关功能目前是第 3 阶段的 ECMAScript 标准,并将很快在所有主要浏览器中发布。
因此,TypeScript 最近添加了这些类型:https://github.com/microsoft/TypeScript/issues/57228
这些将在下一个版本中作为 5.5.0 版本的一部分发布。但是您需要将 TypeScript 编译器选项中的“target”设置为“esnext”才能使用这些新类型。
请参阅游乐场链接。