Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript error when passing parameters between functions

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);
}
like image 911
Danny Delott Avatar asked Mar 04 '23 22:03

Danny Delott


1 Answers

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.

like image 178
jonrsharpe Avatar answered Mar 15 '23 23:03

jonrsharpe