Understanding Generics in TypeScript

Photo by Nubelson Fernandes on Unsplash

In TypeScript, generics are a powerful feature that allows us to create reusable and flexible components. Much like function arguments allow us to pass varying data to a function, generics enable us to work with a variety of types while still maintaining consistent behavior and type safety.

What are Generics?

Generics can be thought of as variables for types. They allow you to define a placeholder for a type that can be assigned at a later point in time, usually when a function, class, or interface is used, rather than when it’s defined.

Why Use Generics?

The use of generics leads to more flexible and reusable code. Without generics, you might find yourself writing overloads of functions or duplicating code for each type you want to support. Generics help avoid this by providing a way to use types as parameters.

Generics in Action

Let’s dive into a simple example to demonstrate how generics enhance reusability while preserving type integrity.

function identity<T>(arg: T): T {
return arg;
}

In this function, T is a type variable. When the function is called, TypeScript will determine the value of T based on the provided argument.

let output = identity<string>("myString");  // type of output will be 'string'

let numberOutput = identity<number>(100); // type of output will be 'number'

Here, we explicitly set T to be string and number, but TypeScript can also infer the type:

let output = identity("myString");  // type of output is inferred to be 'string'

let numberOutput = identity(100); // type of output is inferred to be 'number'

Advanced Generic Patterns

Generics can also be used in complex structures, such as interfaces and classes.

interface GenericIdentityFn<T> {
(arg: T): T;
}

function identity<T>(arg: T): T {
return arg;
}

let myIdentity: GenericIdentityFn<number> = identity;

In this example, we have an interface GenericIdentityFn that describes a function with a generic parameter T. The identity function fits this description and thus can be assigned to a variable of type GenericIdentityFn<number>.

Conclusion

Generics are an essential tool in TypeScript, providing the ability to create components that can work over a variety of types rather than a single one. This brings the flexibility of dynamically typed languages to TypeScript while maintaining strong typing and reducing redundancy.

,