G

Generics

Generics allow you to write reusable code that works with multiple types while maintaining type safety.

Code

typescript
1// Generic function
2function identity<T>(value: T): T {
3 return value;
4}
5
6const num = identity(42); // type: number
7const str = identity("hello"); // type: string
8
9// Generic with constraints
10interface 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: 5
20logLength([1, 2, 3]); // Length: 3
21// logLength(42); // Error: number doesn't have length
22
23// Generic interface
24interface 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 class
37class 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()); // 2
57
58// Multiple type parameters
59function 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