CodeWithMihir

TypeScript Tutorial

TypeScript Generic Constraints Explained

Learn how generic constraints work in TypeScript using extends, object requirements, keyof, and practical reusable helper examples.

Welcome back! I am Mihir, and in this lesson we will learn generic constraints in TypeScript.

Generic constraints let you limit what types a generic can accept.


The Problem

function getLength<T>(value: T): number {
  return value.length;
}

This is invalid because TypeScript does not know whether T has a length property.


Basic Generic Constraint

function getLength<T extends { length: number }>(value: T): number {
  return value.length;
}

Now T must have a length property.

Valid:

getLength("hello");
getLength([1, 2, 3]);

Invalid:

getLength(123);

Constraint with Object Shape

function printName<T extends { name: string }>(value: T): void {
  console.log(value.name);
}

printName({ name: "Mihir", age: 28 });

The object can have extra properties, but it must have name.


Constraint with Interfaces

interface HasId {
  id: number;
}

function findById<T extends HasId>(items: T[], id: number): T | undefined {
  return items.find((item) => item.id === id);
}

Any item type is allowed as long as it has id.


Constraint with keyof

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

const user = {
  id: 1,
  name: "Mihir",
};

const name = getProperty(user, "name");

K extends keyof T means the key must be a real key of the object.

Invalid:

getProperty(user, "email");

Why Constraints Are Useful

Constraints let you keep generics flexible but not too loose.

Without constraints, TypeScript cannot safely allow property access.

With constraints, you can say:

T can be any type, but it must have these features.

Quick Recap

  • Generic constraints limit what a generic can accept.
  • Use extends to define a constraint.
  • Constraints allow safe property access.
  • Objects can have extra properties beyond the constraint.
  • K extends keyof T is a powerful pattern for safe object keys.

Next up, we will learn the keyof Operator →.