Skip to content

Instantly share code, notes, and snippets.

@Gfast2
Created March 24, 2020 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gfast2/361f7b21bc46f95eac3f71829c6159ad to your computer and use it in GitHub Desktop.
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:
// 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