G
Generics
Generics allow you to write reusable code that works with multiple types while maintaining type safety.
Code
typescript
1// Generic function2function identity<T>(value: T): T {3 return value;4}5 6const num = identity(42); // type: number7const str = identity("hello"); // type: string8 9// Generic with constraints10interface HasLength {11 length: number;12}13 14function logLength<T extends HasLength>(value: T): T {15 console.log(`Length: ${value.length}`);16 return value;17}18 19logLength("hello"); // Length: 520logLength([1, 2, 3]); // Length: 321// logLength(42); // Error: number doesn't have length22 23// Generic interface24interface Result<T> {25 data: T;26 success: boolean;27 timestamp: Date;28}29 30const userResult: Result<{ name: string }> = {31 data: { name: "Alice" },32 success: true,33 timestamp: new Date(),34};35 36// Generic class37class Stack<T> {38 private items: T[] = [];39 40 push(item: T): void {41 this.items.push(item);42 }43 44 pop(): T | undefined {45 return this.items.pop();46 }47 48 peek(): T | undefined {49 return this.items[this.items.length - 1];50 }51}52 53const numberStack = new Stack<number>();54numberStack.push(1);55numberStack.push(2);56console.log(numberStack.pop()); // 257 58// Multiple type parameters59function pair<K, V>(key: K, value: V): [K, V] {60 return [key, value];61}62 63const kvPair = pair("name", "Alice"); // [string, string]64const mixedPair = pair(1, true); // [number, boolean]Run this example locally
$ npx ts-node types/generics.ts