programming icon indicating copy to clipboard operation
programming copied to clipboard

[Typescript] Create example of inferring return type depending on argument value

Open AlexanderArvidsson opened this issue 5 years ago • 0 comments

I recently stumbled across a method of inferring the type of the return value depending on the value of the argument. The use-case for me was creating an API that would, given a path to a resource, automatically return the correct type for that specific resource.

Here is an example demonstrating intended functionality:

interface SomeType {
  a: number;
}

interface OtherType {
  b: number;
}

// In this case, both a and a2 will be of type SomeType
const a = pathFetch(pathMap.someResource);
const a2 = pathFetch("/v1/some_resource");

// In this case, b will be of type OtherType
const b = pathFetch(pathMap.otherType);

AlexanderArvidsson avatar Oct 02 '20 22:10 AlexanderArvidsson