Typescript: How to satisfy union type with function and arguments

147 Views Asked by At

The union of (arg: string) => void and (arg: number) => void is (arg: never) => void, because no value can be a string and a number at the same time. But how can I work around this issue in the following example?

type Test<T, U> =
  | {
      func: (arg: T) => void;
      data: T;
    }
  | {
      func: (arg: U) => void;
      data: U;
    };

function test<T, U>(x: Test<T, U>) {
  x.func(x.data);
}

In this example, x.data should always be of the correct type to satisfy the function argument, but typescript can't see it and errors with Argument of type 'string | number' is not assignable to parameter of type 'never'.

EDIT: My use case is the following: Our application has some code to handle navigation between pages. Each possible page is represented by something like this:

type Route<T> = {
  extractData: (url: string) => T;
  encodeDataToURL: (data: T) => string;
  getTitle: (data: T) => string;
  render: (data: T) => DOM.Element;
}

The router handles all routes, so calling the current route's extractData yields HomePageData | SearchPageData | .... When we would call getTitle or render, since it was the same object that produced the data, it should still work fine, but typescript seems oblivious to this.

0

There are 0 best solutions below