TS Basic Generics

Generics in TypeScript allow you to create reusable components that work with a variety of types, providing greater flexibility and type safety. They are especially useful for functions, classes, and interfaces.

Key Topics

Generic Functions

Generic functions allow you to define a function with a placeholder type that can be specified when the function is called.

function identity(value: T): T {
    return value;
}

console.log(identity("Hello")); // Hello
console.log(identity(42));      // 42

Output

Hello

42

Explanation: The identity function uses a generic type T, which allows the function to accept and return values of any specified type.

Generic Classes

Generic classes allow you to define a class with type parameters, enabling type-safe properties and methods.

class Box {
    private content: T;

    constructor(content: T) {
        this.content = content;
    }

    getContent(): T {
        return this.content;
    }
}

const stringBox = new Box("TypeScript");
console.log(stringBox.getContent()); // TypeScript

const numberBox = new Box(123);
console.log(numberBox.getContent()); // 123

Output

TypeScript

123

Explanation: The Box class uses a generic type parameter T, which is specified when creating an instance of the class.

Generic Interfaces

Generic interfaces allow you to define the shape of objects with flexible types.

interface Pair {
    key: K;
    value: V;
}

const numberStringPair: Pair = { key: 1, value: "One" };
console.log(numberStringPair.key);   // 1
console.log(numberStringPair.value); // One

Output

1

One

Explanation: The Pair interface uses two generic type parameters K and V, making it versatile for key-value pair representations.

Key Takeaways

  • Generic Functions: Create flexible and reusable functions that work with any type.
  • Generic Classes: Define type-safe classes with flexible type parameters.
  • Generic Interfaces: Shape objects with adaptable type specifications.
  • Best Practice: Use generics to enforce type safety while maintaining flexibility.