Skip to content

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

Open

Description

@AlexanderArvidsson

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);

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions