我有两个错误的函数,我试图转换为TypeScript。问题在于Set
import type {Set} from 'typescript'
function union<T>(setA: Set<T>, setB: Set<T>) {
const _union = new Set(setA);
for (const elem of setB) {
_union.add(elem)
}
return _union
}
第一个错误出现在第4行:new Set(setA)
第二个错误在第5行:TS2769: No overload matches this call.
for (const elem of setB)
TS2495:类型'Set '不是数组类型或字符串类型。
否则,此函数按预期工作。
tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"module": "commonjs",
"target": "es5",
"lib": ["esnext"],
"esModuleInterop": true
},
"exclude": [
"node_modules"
],
"include": [
"src/**/*"
]
}
问题
当您使用import { Set } from 'typescript'
时,您实际上导入了Set对象的类型定义。然后,我相信,类型定义与javascript给出的Set对象重叠(不需要导入它)。如果你在typescript
中查找Set
类型定义,你会发现Set
代表一个Typescriptinterface
:
interface Set<T> extends ReadonlySet<T>, Collection<T> {
add(value: T): this;
delete(value: T): boolean;
}
但是当您调用new Set()
时,解释器寻找构造函数来初始化对象,但是它没有找到,因为导入的Set
是一个接口。这就是为什么你会得到错误:
No overload matches this call.
:导入的Set
没有构造函数,所以Typescript找不到任何可以初始化Set
的相关函数。TS2495: Type 'Set ' is not an array type or a string type.
:Set
确实不是数组类型,也不是字符串类型,因为它是interface
。
的解决方案javascript给了我们Set对象,不需要导入它,你根本不需要导入它。此外,您也不必导入Set
类型定义,因为它是内置的。