programming
programming copied to clipboard
[Typescript] Added example of inferring type by argument
Pull Request checklist -
- [x] This pull request fixes #2176
- [x] The directory structure is of the form (typescript-infer-type-by-argument)
- [x] Don't duplicate stuff.
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.