[TypeScript] What is Generics?

·

3 min read

[TypeScript] What is Generics?

In the world of TypeScript, generics provide a powerful way to write reusable and flexible code. Generics allow you to create functions, classes, and interfaces that work with a variety of types, providing better type safety and enabling the creation of more versatile software components.

At its core, generics in TypeScript allow you to define placeholders for types that will be specified when the code is used. This enables you to write code that can work with different data types without sacrificing type safety.


How to use Generics?

  • Generic Functions

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

let result = identity<string>("Hello, generics!");
console.log(result); 
// Output: Hello, generics!

In this example, identity is a generic function that takes a type parameter T. The function returns the same type it receives as an argument. When calling the function, you can explicitly specify the type, or TypeScript can infer it for you.

  • Generic Classes

class Box<T> {
    private value: T;

    constructor(initialValue: T) {
        this.value = initialValue;
    }

    getValue(): T {
        return this.value;
    }
}

let numberBox = new Box<number>(42);
console.log(numberBox.getValue()); 
// Output: 42

let stringBox = new Box<string>("Generics are awesome!");
console.log(stringBox.getValue()); 
// Output: Generics are awesome!

In this example, Box is a generic class that can hold a value of any type.


When to use Generics?

interface Person {
    name: string;
    age: number;
}

const people: Person[] = [
    { name: "Alice", age: 30 },
    { name: "Bob", age: 25 },
    { name: "Charlie", age: 35 },
];

function sortByProperty<T, K extends keyof T>(array: T[], property: K): T[] {
    return array.slice().sort((a, b) => a[property] - b[property]);
}

// Sort people by age
const sortedByAge = sortByProperty<Person, "age">(people, "age");
console.log(sortedByAge);
// Output: [ { name: 'Bob', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Charlie', age: 35 } ]

// Sort people by name
const sortedByName = sortByProperty<Person, "name">(people, "name");
console.log(sortedByName);
// Output: [ { name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 35 } ]

In this example, the sortByProperty function is a generic function that takes an array of objects of type T and a property key of type K, which must be a key of T. The function uses the property key to sort the array of objects based on that property.

This generic function allows you to sort arrays of different types of objects by different properties, providing a reusable and type-safe solution. The type constraints ensure that the property passed to the function is a valid property of the objects in the array.

This type of generic function is especially useful in scenarios where you have various types of objects and need to perform sorting or other operations based on different properties.