Last active
November 21, 2023 13:58
-
-
Save maxgfr/73c3cddd025aee88960f8fb773660fd7 to your computer and use it in GitHub Desktop.
getValue with type inference in typescript
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 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