Skip to main content

Generics

Generics is a powerful feature in TypeScript that allows you to create reusable and flexible types. In this tutorial, we'll explore Generics in TypeScript, how to use them, and how they can help you write better, more robust code.

What are Generics?

In TypeScript, generics are a way to create reusable components that can work with a variety of data types, not just one. Generics are like placeholders, or variables, for types. They're often represented with the letter T.

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

In this simple example, T is a type variable — a stand-in for any type. This function will return whatever is passed to it, and TypeScript will preserve the type information.

Using Generics

You can use generics just like any other type in TypeScript. Here's how you can use the identity function we defined above:

let output = identity<string>("myString");

By using <string> after the function name, we're telling TypeScript that we want to use this function as a generic function that works with strings.

Generic Types

You can also define your own generic types. This can be useful when you want to define a type that works with a variety of other types. Here's an example:

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

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

let myIdentity: GenericIdentityFn<number> = identity;

Here we've defined a new interface GenericIdentityFn that encodes our earlier identity function as a generic function type.

Generic Classes

Just like interfaces, classes can also be generic. A generic class has a similar shape to a generic interface.

class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

In this example, we have a GenericNumber class. This class has a generic parameter T that's used in several places: as the type for zeroValue, and as the type for the parameters and return value of the add method.

Conclusion

Generics are a powerful feature in TypeScript that allow for the creation of reusable components which can operate over a variety of types rather than a single one. This provides much-needed flexibility while still maintaining strong typing. The use of generics can greatly improve the robustness and reusability of your TypeScript code.

We hope this guide has been helpful in understanding the concept of generics in TypeScript. Happy coding!