TypeScript Types and Generics/Constrain a key parameter with `keyof`

Accept only valid property names for a given object type.

Section: Generics

Constrain a key parameter with `keyof`

typescript
typescript
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
Explanation

This is one of the most useful generic patterns in application code.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Generics
Generic identity function
Use a type parameter for reusable function typing.
OpenIn sheettypescriptsame section
Generic array helper
Write array helpers that preserve element types.
OpenIn sheettypescriptsame section
Generic interface
Parameterize a reusable interface.
OpenIn sheettypescriptsame section
Constrain generic types
Require a minimum shape for a type parameter.
OpenIn sheettypescriptsame section
Use `keyof`
Get a union of property names from a type.
OpenIn sheettypescript2 tag match
Use indexed access types
Get a nested property type from another type.
OpenIn sheettypescript2 tag match