Skip to content

Instantly share code, notes, and snippets.

@cellog
Created August 30, 2019 19:12
Show Gist options
  • Save cellog/3f6faed194e493b1c06249304b18e445 to your computer and use it in GitHub Desktop.
Save cellog/3f6faed194e493b1c06249304b18e445 to your computer and use it in GitHub Desktop.
Inferring a type with a generic
// the example from typescript's docs
// The type T is never explicitly specified and can be any type that supports keyof
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a"); // okay
getProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.
// new example not in the typescript docs:
const y = { totally: 'different' }
getProperty(y, "a"); // error: Argument of type 'a' isn't assignable to 'totally'.
getProperty(y, "totally"); // okay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment