TypeScript错误设置类型



我有两个错误的函数,我试图转换为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)

TS2769: No overload matches this call.

第二个错误在第5行: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类型定义,因为它是内置的。

最新更新