Start Coding

Topics

Generics in TypeScript

Generics are a powerful feature in TypeScript that enable you to create reusable components. They allow you to write flexible, type-safe code that can work with multiple data types.

What are Generics?

Generics provide a way to make components work with any data type and not restrict to one data type. They help you create a component that can work over a variety of types rather than a single one.

Basic Syntax

To define a generic function or class, use angle brackets <T> where T is a type parameter:

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

let output = identity<string>("myString");
console.log(output);  // Output: myString

Why Use Generics?

  • Type Safety: Generics ensure that the type you're using is consistent throughout the component.
  • Code Reusability: Write a function once and use it with different types.
  • Flexibility: Generics allow your functions and classes to work with any data type.

Generic Constraints

You can restrict the types that a generic type parameter can accept using the extends keyword:

interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);  // Now we know it has a .length property
    return arg;
}

For more advanced usage of generics with constraints, check out the Generic Constraints guide.

Generic Classes

Generics can also be used with classes:

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; };

Best Practices

  • Use generics when you want to create a component that can work with a variety of types.
  • Name your generic types meaningfully. While T is common, descriptive names like TEntity or TKey can improve readability.
  • Use constraints to limit the types that can be used with your generic component when necessary.

Related Concepts

To deepen your understanding of TypeScript and how it relates to generics, explore these related topics:

Generics are a fundamental concept in TypeScript that enable you to write more flexible and reusable code. By mastering generics, you'll be able to create robust, type-safe components that can work with a variety of data types.