Created
August 30, 2019 19:35
-
-
Save cellog/4081005bcd4fa17de4193ea51903ef7b to your computer and use it in GitHub Desktop.
Non-Inferred Generics
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
// the example from typescript's docs | |
function getProperty<T, K extends keyof T>(obj: T, key: K) { | |
return obj[key]; | |
} | |
interface FourLetters { | |
a: number | |
b: number | |
c: number | |
d: number | |
} | |
let x = { a: 1, b: 2, c: 3, d: 4 } | |
// calling generic explicitly (the first way I thought generics could be called) | |
getProperty<FourLetters, keyof FourLetters>(x, "a"); // okay | |
// providing a default value in the definition | |
function getProperty_withDefaults<T extends {} = {}, K extends keyof T = keyof T>(obj: T, key: K) { | |
return obj[key]; | |
} | |
// calling a generic with inference even though it has a default | |
getProperty_withDefaults({ a: 1 }, 'a') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment