I am creating a library written in Typescript that exposes a class with a constructor that takes a single type parameter Set.
This library will be used by an application written in javascript, I need to check that this parameter is valid Set. My code currently looks something like this:
export class Something {
private mySet: Set<string>;
constructor(aSet: Set<string>) {
if (!(aSet instanceof Set)) {
throw new TypeError('Invalid parameter');
}
this.mySet = aSet;
}
}
I created a test package that validates this code:
it('should throw if instantiate without parameter', () => {
expect(() => {
new Something();
}).toThrow();
});
it('should not throw if parameter is a Set', () => {
expect(() => {
new Something(new Set([1, 2]));
}).not.toThrow();
});
The Typescript compiler rightly showed error TS2554: Expected 1 arguments, but got 0in the first test.
The only way to find this problem is to change the constructor signature and declare my parameter as optional with the type any, but this does not seem to be correct ...
export class Something {
private mySet: Set<string>;
constructor(aSet?: any) {
if (!(aSet instanceof Set)) {
throw new TypeError('Invalid parameter');
}
this.mySet = aSet;
}
}
?