Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Typescript] Added example of inferring type by argument #2177

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

AlexanderArvidsson
Copy link

@AlexanderArvidsson AlexanderArvidsson commented Oct 2, 2020

Pull Request checklist -

The use-case that I needed this for involved creating an API fetcher that would automatically infer the type depending on the path of the resource you specify.
All paths to resources are located in a key-value map:

const pathMap = {
  someResource: "/v1/some_resource",
  otherType: "/v1/other_resource",
} as const;

and all types for said resources are also in a key-value map:

type PathTypes = {
  someResource: SomeType;
  otherType: OtherType;
};

I could have made it simpler by having the actual path as the key for the PathTypes map, but that would be ugly in my opinion.
The implementation works by finding the key of the path in the argument, then using that key to find the type that the resource belongs to.

One bonus of this is that the API only accepts paths that are specified in the path map, because otherwise the type would be unknown which is undesirable behavior.

I am unsure if this is the best method of doing this, but it works in my scenario.

@AlexanderArvidsson AlexanderArvidsson changed the title Added example of inferring type by argument [Typescript] Added example of inferring type by argument Oct 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

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