I have 2 errors with a function that I have attempted to convert to TypeScript. The problem is with the parameters which are of type 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
}
The first error is on line 4: new Set(setA)
TS2769: No overload matches this call.
The second error is on line 5: for (const elem of setB)
TS2495: Type 'Set ' is not an array type or a string type.
Otherwise, this function works as expected.
tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"module": "commonjs",
"target": "es5",
"lib": ["esnext"],
"esModuleInterop": true
},
"exclude": [
"node_modules"
],
"include": [
"src/**/*"
]
}
CodePudding user response:
The Problem
When you import { Set } from 'typescript'
, you actually import the type definition for the Set object.
Then, I believe, the type definition overlaps the Set object given by javascript(without the need to import it).
If you look for the Set
type definition in typescript
, you'll find out that Set
represents a Typescript interface
:
interface Set<T> extends ReadonlySet<T>, Collection<T> {
add(value: T): this;
delete(value: T): boolean;
}
But when you call new Set()
, the interpreter looks for a constructor to initiate the object, but it doesn't find one, as the imported Set
is an interface. And that is why you get the errors:
No overload matches this call.
: There is no constructor for the importedSet
, so Typescript doesn't find any relevant function that could initiate theSet
.TS2495: Type 'Set ' is not an array type or a string type.
:Set
is indeed not an array type, nor a string as it is aninterface
.
The Solution
As javascript gives us the Set object, without any need to import it, you don't have to import it at all.
In addition, you also don't have to import the Set
type definition, as it is built in.