Created
January 30, 2024 09:16
-
-
Save tadeaspetak/54cd57ad12ad6ca9d7e6a610d837a1bd to your computer and use it in GitHub Desktop.
URL Factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const urlFactory = { | |
verify: (token: string) => `/verify/${token}`, | |
deed: ({ orgId, deedId }: { deedId: number; orgId: number }) => `/deed/${orgId}/${deedId}` | |
} | |
// Turn a factory object (like the one above) into a mapped type. | |
type URLFactoryMapped<T extends Record<keyof T, (...args: any) => any>> = | |
{ [K in keyof T]: (...args: Parameters<T[K]>) => ReturnType<T[K]> } | |
const url = <T extends keyof typeof urlFactory>(key: T, ...args: Parameters<typeof urlFactory[T]>) => { | |
// This is necessary for TS to understand that the function it gets through `key` | |
// has the arguments of the function it gets through `key`. | |
// https://stackoverflow.com/a/75514493/3844098 | |
const _urlFactory: URLFactoryMapped<typeof urlFactory> = urlFactory; | |
return _urlFactory[key](...args); | |
} | |
console.log({ | |
verify: url('verify', 'my-token'), | |
deed: url('deed', { deedId: 1, orgId: 2 }), | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment