Created
August 30, 2019 19:12
-
-
Save cellog/3f6faed194e493b1c06249304b18e445 to your computer and use it in GitHub Desktop.
Inferring a type with a generic
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 | |
// 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