Menu

Generic Constraints and keyof

Lesson 3: Generic Constraints and keyof

What is a constraint?

A constraint limits what a type parameter can be, using extends. Inside the function, you can then safely use what the constraint guarantees.

Constraint Allows Lets you use
T extends { id: string } Any type with a string id item.id
`T extends string number` Strings or numbers
K extends keyof T Only property names of T obj[key], typed correctly
T extends unknown[] Any array .length, iteration

Example

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

const milk = { id: 'p1', name: 'Milk 1L', price: 6400, inStock: true };

const price = getProperty(milk, 'price');     // number
const inStock = getProperty(milk, 'inStock'); // boolean
getProperty(milk, 'colour');
// Error: Argument of type '"colour"' is not assignable to parameter of type '"id" | "name" | "price" | "inStock"'.

function sortBy<T, K extends keyof T>(items: T[], key: K): T[] {
  return [...items].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0));
}

sortBy(catalogue, 'price');

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
longest('rice', 'basmati');   // string
longest([1, 2], [1, 2, 3]);   // number[]

How it works

  • keyof T is the union of T's property names: 'id' | 'name' | 'price' | 'inStock'.
  • T[K] is an indexed access type: the type of property K on T. It makes getProperty return the exact property type.
  • Without a constraint, a.length inside longest would be an error, because not every type has length.

Common mistakes

Mistake Effect Fix
Using key: string for property names Typos accepted, result is any or an error Use K extends keyof T
Constraining too tightly (T extends Product) Function cannot be reused Constrain to only what the function uses
Accessing properties not covered by the constraint Error Add them to the constraint

Key takeaways

  • extends tells TypeScript what a type parameter must support.
  • K extends keyof T with T[K] gives fully typed property access.

Try it: Write pluck<T, K extends keyof T>(items: T[], key: K): T[K][] and use it to get all product names and all prices.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details