I'm trying to create a function, that takes array of numbers or array of string and return Set from that array, like this:
const f = (arr: number[] | string[]): number[] | string[] => {
return [...new Set(arr)];
}
And getting an error:
No overload matches this call.
Overload 1 of 2, '(iterable?: Iterable | null | undefined): Set', gave the following error.
Argument of type 'number[] | string[]' is not assignable to parameter of type 'Iterable | null | undefined'.
Type 'string[]' is not assignable to type 'Iterable'.
The types returned by 'Symbol.iterator.next(...)' are incompatible between these types.
Type 'IteratorResult<string, any>' is not assignable to type 'IteratorResult<number, any>'.
Type 'IteratorYieldResult' is not assignable to type 'IteratorResult<number, any>'.
Type 'IteratorYieldResult' is not assignable to type 'IteratorYieldResult'.
Type 'string' is not assignable to type 'number'.
Overload 2 of 2, '(values?: readonly number[] | null | undefined): Set', gave the following error.
Argument of type 'number[] | string[]' is not assignable to parameter of type 'readonly number[] | null | undefined'.
Type 'string[]' is not assignable to type 'readonly number[]'.
Type 'string' is not assignable to type 'number'.
I can change the incoming type from number[] | string[] to (number | string)[] but it means that in the array could be numbers and strings at the same time, that is not what I want.
const f = (arr: (number | string)[]): (number | string)[] => {
return [...new Set(arr)];
}
f([1,2,3]); // ok
f(['1','2','3']); // ok
f([1,2,'3','4']); // ok, but should be err
f([true, {}, 1]); // err, like it should be