Skip to main content

Generics & Constraints in TypeScript (Live Playground)

In this tutorial, we will explore generics and constraints in TypeScript. Understanding how to use generics and constraints will help you write reusable and type-safe code.

Generics​

Generics allow you to create reusable and type-safe functions and classes that can work with different types. They can be used to create utility functions, such as a function that merges two objects or a function that returns the length of an array:

TypeScript
function merge<T, U>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}

const person = { name: 'John Doe' };
const employee = { title: 'Software Developer' };

const fullTimeEmployee = merge(person, employee);
console.log(fullTimeEmployee); // Output: { name: 'John Doe', title: 'Software Developer' }

In this example, we create a generic function merge that accepts two objects of different types and returns an object that combines the properties of both objects.

Live Playground, Try it Yourself

Constraints​

Constraints allow you to create more restrictive generics that enforce certain conditions on the types used. They can be used to create more type-safe utility functions and classes:

TypeScript
interface Lengthwise {
length: number;
}

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

console.log(getLength('Hello, world!')); // Output: 13
console.log(getLength([1, 2, 3, 4])); // Output: 4

In this example, we create an interface Lengthwise and a generic function getLength that accepts an item of a type that extends Lengthwise. The getLength function returns the length of the item.

Live Playground, Try it Yourself

Using Generics and Constraints​

Generics and constraints can be used in a variety of scenarios to create more reusable and type-safe code:

  1. Creating utility functions and classes that can work with different types, for example, by creating a function that merges two objects or a function that returns the length of an array.
  2. Enforcing certain conditions on the types used in generics, for example, by creating a function that accepts items with a length property.
  3. Writing more expressive and type-safe code in scenarios where types depend on other types, for example, by creating a generic Promise type that can be used with different types of values.

Conclusion​

In this tutorial, we have explored generics and constraints in TypeScript. Understanding how to use generics and constraints effectively will enable you to create more reusable and type-safe code.