This pattern is throwing the TypeScript error:
Argument of type '(string | number)[]' is not assignable to parameter of type 'string[] | number[]'
function foo(value: string | number) {
return bar([value]); // <- TypeScript error
}
function bar(valueList: string[] | number[]) {
..does something...
}
I understand this is because TypeScript compiler will see this as an array with a mix of strings and numbers.
Is there a type-safe way to accomplish this? I can only think to cast to any[]
which feels bad:
function foo(value: string | number) {
const valueList: any[] = [value];
return bar(valueList);
}
One way to do this is declaration merging; define two separate interfaces for your function (see function types), then a single implementation of it:
interface Foo {
(value: string): void;
}
interface Foo {
(value: number): void;
}
const foo: Foo = function (value) {
return bar([value]);
}
This will keep the two types separate, as only one of those interfaces can be called through at any given time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With