Created
April 13, 2023 14:59
-
-
Save nielk/3d183e04283638d0b159cbbb54cd3409 to your computer and use it in GitHub Desktop.
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 obj = { | |
'a': (a: string, b: number): string => `${a}: ${b}`, | |
'b': (b: number): string => `${b}`, | |
'c': (): number => 42, | |
} | |
const getFn = <K extends keyof typeof obj>(key: K, ...params: Parameters<typeof obj[K]>) => { | |
return (obj[key] as (...args: Parameters<typeof obj[K]>) => ReturnType<typeof obj[K]>)(...params) | |
} | |
const a1: string = getFn('a', 'a', 2) // ok | |
const a2: string = getFn('a', 'a') // not ok | |
const b1: string = getFn('b', 42) // ok | |
const b2: string = getFn('b') // not ok | |
const c1: number = getFn('c') // ok | |
const c2: string = getFn('c') // not ok: Type 'number' is not assignable to type 'string' | |
const c3: number = getFn('c', 1) // not ok |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment