I am currently working on a function that takes an array of numbers or strings and returns a Set containing unique elements:
const f = (arr: number[] | string[]): number[] | string[] => {
return [...new Set(arr)];
}
However, I am encountering an error message:
The call does not match any overload.
Overload 1 of 2, '(iterable?: Iterable | null | undefined): Set', produced the following error.
The argument 'number[] | string[]' cannot be assigned to a parameter of type 'Iterable | null | undefined'.
Type 'string[]' cannot be assigned to type 'Iterable'.
The types returned by 'Symbol.iterator.next(...)' are incompatible between these types.
Type 'IteratorResult<string, any>' cannot be assigned to type 'IteratorResult<number, any>'.
Type 'IteratorYieldResult' cannot be assigned to type 'IteratorResult<number, any>'.
Type 'IteratorYieldResult' cannot be assigned to type 'IteratorYieldResult'.
Type 'string' cannot be assigned to type 'number'.
Overload 2 of 2, '(values?: readonly number[] | null | undefined): Set', produced the following error.
The argument 'number[] | string[]' cannot be assigned to a parameter of type 'readonly number[] | null | undefined'.
Type 'string[]' cannot be assigned to type 'readonly number[]'.
Type 'string' cannot be assigned to type 'number'.
I can change the input type from number[] | string[]
to (number | string)[]
, but this means that the array could contain both numbers and strings simultaneously, which is not what I intend.
const f = (arr: (number | string)[]): (number | string)[] => {
return [...new Set(arr)];
}
f([1,2,3]); // okay
f(['1','2','3']); // okay
f([1,2,'3','4']); // okay, should actually be error
f([true, {}, 1]); // should be an error, as expected