Welcome to this tutorial on understanding generics in TypeScript. The main goal of this tutorial is to help you understand what generics are, why they are useful, and how to use them in your TypeScript code.
After completing this tutorial, you should be able to:
- Understand the concept of generics in TypeScript
- Use generics to create flexible and reusable components
- Apply best practices when using generics
Prerequisites: This tutorial assumes that you already have a basic understanding of TypeScript. If you are new to TypeScript, I recommend you to first familiarize yourself with the basics of TypeScript.
Generics are a feature of TypeScript that allow you to write reusable and flexible types. They are like variables for types, allowing you to write code that works over a variety of types, rather than a single one.
Here's a simple example:
function identity<T>(arg: T): T {
return arg;
}
In the code above, we defined a generic function identity
. The <T>
syntax is a placeholder for the type that the function will work with. This type is then used as a parameter type and as the return type.
T
is a common choice, but you can use any name you like.Let's look at a few more examples of using generics in TypeScript.
function printAll<T>(args: T[]): void {
args.forEach((arg) => console.log(arg));
}
printAll<string>(["Apple", "Banana", "Cherry"]); // output: Apple, Banana, Cherry
In this example, T[]
is a generic array type. The function printAll
can work with arrays of any type.
class Box<T> {
constructor(public content: T) {}
public printContent(): void {
console.log(this.content);
}
}
let box = new Box<number>(123);
box.printContent(); // output: 123
Here, Box<T>
is a generic class. It can hold and print content of any type.
In this tutorial, we looked at generics in TypeScript. We learned what they are, how to use them, and went through several examples. Generics are a powerful feature that makes your code more flexible and reusable.
Now that you've learned about generics, you can start using them in your TypeScript code. For further learning, you can read the official TypeScript documentation on generics.
Pair
that holds a pair of elements of any type.function reverse<T>(arr: T[]): T[] {
return arr.reverse();
}
console.log(reverse<number>([1, 2, 3])); // output: [3, 2, 1]
class Pair<T, U> {
constructor(public first: T, public second: U) {}
}
let pair = new Pair<number, string>(1, "apple");
console.log(pair); // output: Pair { first: 1, second: 'apple' }
For further practice, you can try creating more functions and classes that use generics. The more you use them, the more comfortable you'll get with them.