Skip to content

Instantly share code, notes, and snippets.

@nielk
Created April 13, 2023 14:59
Show Gist options
  • Save nielk/3d183e04283638d0b159cbbb54cd3409 to your computer and use it in GitHub Desktop.
Save nielk/3d183e04283638d0b159cbbb54cd3409 to your computer and use it in GitHub Desktop.
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