Generics in Typescript allow us to create flexible and reusable components by providing a way to define types that are used as placeholders.
These types can be specified when using the component, allowing for a wide range of type-safe behaviours.
Generics are particularly useful when working with functions and classes that need to handle different data types without sacrificing type safety.
Generics Support Type Safety provide compile-time type checking, ensuring type safety without the need for explicit type casting.
One of the major uses of generic type is Code Reusability, we can write generic classes and methods that work with various data types, and prevent code duplication.
Generics help in performance improvement by eliminating the need for runtime type checking and conversions.
Generics make the code more readable by providing type information at the declaration level.
function swapMethod<T>(a: T, b: T): [T, T] { return [b, a]; } // Usage const result = swapMethod <string>("Hello", "World"); console.log(result); // Output: ["World", "Hello"] const result2 = swapMethod <number>(10, 20); console.log(result2); // Output: [20, 10]
T is a generic type parameter. The function swap can be used with any data type, and TypeScript will enforce the correct usage based on the provided types.
Generics can also be used with classes.
class Box<T> { private value: T; constructor(value: T) { this.value = value; } getValue(): T { return this.value; } } // Usage const numberBox = new Box<number>(110); console.log(numberBox.getValue()); // Output: 110 const stringBox = new Box<string>("Hello World, Typescript!"); console.log(stringBox.getValue()); // Output: "Hello World, Typescript!"
the Box class is generic, allowing it to hold values of any type.
TypeScript provides utility types that work well with generics, such as Partial, Readonly, and Record.
interface Person { name: string; age: number; } function makePartial<T>(obj: T): Partial<T> { return obj; } const partialPerson: Partial<Person> = makePartial({ name: "Alice" }); // partialPerson is { name?: string; age?: number; } console.log(partialPerson) // Output: { "name": "Alice" } const partialPerson2: Partial<Person> = makePartial({ name: "Alice", age: 23 }); // partialPerson2 is { name?: string; age?: number; } console.log(partialPerson2) // Ouput: {"name": "Alice", "age": 23 }
These utility types can be used to modify or manipulate generic types.
Partial