programming
programming copied to clipboard
[Typescript] Create example of inferring return type depending on argument value
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);