Skip to content

Instantly share code, notes, and snippets.

@maxgfr
Last active November 21, 2023 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxgfr/73c3cddd025aee88960f8fb773660fd7 to your computer and use it in GitHub Desktop.
Save maxgfr/73c3cddd025aee88960f8fb773660fd7 to your computer and use it in GitHub Desktop.
getValue with type inference in typescript
const getValue = <TObj, Tkey extends keyof TObj> (obj: TObj, key: Tkey) => obj[key]
const result = getValue({a: "hello", b: 2, c: true}, "a")
console.log(result) // defined as string
const result2 = getValue({a: "hello", b: 2, c: true}, "b")
console.log(result2) // defined as number
const result3 = getValue({a: "hello", b: 2, c: true}, "c")
console.log(result3) // defined as boolean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment