Skip to content

Instantly share code, notes, and snippets.

@cellog
Created August 30, 2019 19:35
Show Gist options
  • Save cellog/4081005bcd4fa17de4193ea51903ef7b to your computer and use it in GitHub Desktop.
Save cellog/4081005bcd4fa17de4193ea51903ef7b to your computer and use it in GitHub Desktop.
Non-Inferred Generics
// 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