Type System

TS Generics

Using Generics

TypeScript generics create reusable typed components, like typed arrays.

Introduction to TypeScript Generics

TypeScript generics offer a way to create components that can work with a variety of types, ensuring type safety and reusability. By using generics, you can define a function, interface, or class that works with any data type while maintaining the type constraints you specify. This is particularly useful for building adaptable and flexible code structures.

Basic Syntax of Generics

Generics are defined using angle brackets <> and a placeholder type, often represented by T. This placeholder can be replaced with any type when the function, class, or interface is used. Here is the basic syntax:

In the example above, the identity function takes an argument of type T and returns a value of the same type T. The specific type is determined when the function is called.

Using Generics in Functions

Generics can be particularly useful in functions that need to handle different data types. For example, a generic function can be used to create a typed array:

Here, the createArray function takes a length and a value and returns an array filled with that value. By specifying the generic type T, the function can create arrays of any data type.

Generics in Classes

Classes can also benefit from generics, allowing them to handle various data types while maintaining type safety. Below is an example of a generic class:

The Box class is generic and can store any type of data. When an instance of Box is created, the type is specified, ensuring that only values of that type can be stored.

Generic Interfaces

Interfaces can also be generic, providing flexibility in defining object types that can adapt to different type constraints:

The Pair interface can represent a pair of values with any two types. This makes it highly versatile for different use cases.

Constraints on Generics

Sometimes, you may want to impose constraints on the types that can be used as generic type arguments. TypeScript allows you to specify constraints using the extends keyword:

In this example, the generic type T is constrained to types that have a length property. This provides more control over the types that can be used with the function.