Understanding Generics in TypeScript

Tutorial 1 of 5

Understanding Generics in TypeScript

1. Introduction

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.

2. Step-by-Step Guide

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.

Best Practices:

  • Use clear and concise names for your generic type variables. T is a common choice, but you can use any name you like.
  • Be mindful of when to use generics. They are powerful, but not every function or class needs to be generic.

3. Code Examples

Let's look at a few more examples of using generics in TypeScript.

Example 1: Generic Array

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.

Example 2: Generic Class

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.

4. Summary

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.

5. Practice Exercises

  1. Write a generic function that reverses an array of any type.
  2. Write a generic class Pair that holds a pair of elements of any type.

Solutions

  1. Reversing an array:
function reverse<T>(arr: T[]): T[] {
    return arr.reverse();
}

console.log(reverse<number>([1, 2, 3]));  // output: [3, 2, 1]
  1. Pair class:
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.