Created
March 24, 2020 07:56
-
-
Save Gfast2/361f7b21bc46f95eac3f71829c6159ad to your computer and use it in GitHub Desktop.
You can declare a type parameter that is constrained by another type parameter. For example, here we’d like to get a property from an object given its name. We’d like to ensure that we’re not accidentally grabbing a property that does not exist on the obj, so we’ll place a constraint between the two types:
This file contains hidden or 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
// https://www.typescriptlang.org/docs/handbook/generics.html | |
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'. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment