In TypeScript, generics are a feature that enables you to define functions, interfaces, or classes without explicitly specifying the exact type they operate on. This enhances code flexibility and reusability.
Declaration of Generics:
1. Generic Functions
Generics can be applied to functions. For example, to create a function that accepts an array and returns its first element, you can define it as follows:
typescriptfunction getFirstElement<T>(arr: T[]): T { return arr[0]; } // Usage example let numbers = [1, 2, 3]; let firstNumber = getFirstElement(numbers); // Type inferred as number let strings = ["apple", "banana"]; let firstString = getFirstElement(strings); // Type inferred as string
In this example, <T> is a generic type parameter indicating the function is generic. T is inferred automatically from the arguments provided when calling the function.
2. Generic Interfaces
Generics can also be defined on interfaces, allowing certain properties or methods to support multiple types:
typescriptinterface KeyValuePair<K, V> { key: K; value: V; } // Using the generic interface let item: KeyValuePair<number, string> = { key: 1, value: "Apple" };
In this example, the KeyValuePair interface has two type parameters K and V, representing the types of the key and value, respectively. By specifying <number, string>, we create an object where the key is of type number and the value is of type string.
3. Generic Classes
Generics can also be applied to classes, making them more flexible when handling different data types:
typescriptclass Stack<T> { private elements: T[] = []; push(element: T) { this.elements.push(element); } pop(): T | undefined { return this.elements.pop(); } } // Using the generic class let numberStack = new Stack<number>(); numberStack.push(10); numberStack.push(20); console.log(numberStack.pop()); // Output: 20 let stringStack = new Stack<string>(); stringStack.push("Hello"); stringStack.push("World"); console.log(stringStack.pop()); // Output: "World"
In this example, the Stack class uses the generic type T to represent the type of elements stored in the stack. This allows us to create stacks for specific types, such as number or string.
By using generics, TypeScript code becomes more flexible and reusable while maintaining type safety and integrity.