#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 12 of 48medium

What are Generic Constraints in TypeScript?

Limiting types with extends.

What You'll Learn

  • Constraining generics
  • extends keyword
  • keyof constraint

Generic Constraints

Use extends to limit what types can be passed to a generic.

code.tsTypeScript
// Without constraint - error
function getLength<T>(arg: T): number {
  return arg.length; // Error: T doesn't have length
}

// With constraint
function getLength<T extends { length: number }>(arg: T): number {
  return arg.length; // OK
}

getLength("hello");     // 5
getLength([1, 2, 3]);   // 3
getLength({ length: 10 }); // 10
getLength(123);         // Error: number has no length

Using Interfaces as Constraints

code.tsTypeScript
interface HasId {
  id: number;
}

function printId<T extends HasId>(obj: T): void {
  console.log(obj.id);
}

printId({ id: 1, name: "John" }); // OK
printId({ name: "John" });        // Error: missing id

keyof Constraint

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

const user = { name: "John", age: 30 };
getProperty(user, "name"); // OK
getProperty(user, "email"); // Error: "email" not in user