How to implement generics in TypeScript



Image not found!!

Generics in TypeScript allow you to write functions and classes that work with different data types while maintaining type safety. Here's a basic overview of how to implement generics in TypeScript:

Function with Generics:

typescript
// Basic generic function function identity<T>(arg: T): T { return arg; } // Example usage let result = identity<string>("Hello, TypeScript!"); console.log(result); // Output: Hello, TypeScript! // TypeScript can also infer the type let inferredResult = identity(42); console.log(inferredResult); // Output: 42

Class with Generics:

typescript
// Basic generic class class Box<T> { private value: T; constructor(initialValue: T) { this.value = initialValue; } getValue(): T { return this.value; } } // Example usage let stringBox = new Box<string>("TypeScript"); console.log(stringBox.getValue()); // Output: TypeScript let numberBox = new Box<number>(42); console.log(numberBox.getValue()); // Output: 42

Generic Constraints:

You can also impose constraints on generics to ensure they meet specific criteria:

typescript
interface Lengthwise { length: number; } // Generic function with a constraint function logLength<T extends Lengthwise>(arg: T): void { console.log(arg.length); } // Example usage logLength("Hello"); // Output: 5 logLength([1, 2, 3]); // Output: 3 // logLength(42); // Error: 'number' does not have a 'length' property

Multiple Generic Types:

typescript
// Function with multiple generic types function pair<T, U>(first: T, second: U): [T, U] { return [first, second]; } // Example usage let resultPair = pair("TypeScript", 42); console.log(resultPair); // Output: ["TypeScript", 42]

These are just basic examples, and generics can be used in various scenarios to provide flexibility while maintaining type safety in TypeScript. You can use generics with interfaces, type aliases, and more to create reusable and type-safe code.