TypeScript Essentials
TypeScript Generics
TypeScript Generics
Section titled “TypeScript Generics”Generics allow you to create reusable components that work with multiple types.
Basic Generics
Section titled “Basic Generics”// Without genericsfunction identity(arg: any): any { return arg;}
// With generics - preserves typefunction identity<T>(arg: T): T { return arg;}
const num = identity<number>(42); // numberconst str = identity<string>("hi"); // stringconst inferred = identity(true); // boolean (inferred)Generic Arrays
Section titled “Generic Arrays”function first<T>(arr: T[]): T | undefined { return arr[0];}
const firstNum = first([1, 2, 3]); // numberconst firstStr = first(["a", "b"]); // stringGeneric Interfaces
Section titled “Generic Interfaces”interface Container<T> { value: T; getValue(): T;}
const numContainer: Container<number> = { value: 42, getValue() { return this.value; }};Generic Classes
Section titled “Generic Classes”class Stack<T> { private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
peek(): T | undefined { return this.items[this.items.length - 1]; }}
const numStack = new Stack<number>();numStack.push(1);numStack.push(2);Generic Constraints
Section titled “Generic Constraints”interface HasLength { length: number;}
function logLength<T extends HasLength>(arg: T): T { console.log(arg.length); return arg;}
logLength("hello"); // Works - string has lengthlogLength([1, 2, 3]); // Works - array has length// logLength(123); // Error - number has no lengthMultiple Type Parameters
Section titled “Multiple Type Parameters”function pair<K, V>(key: K, value: V): [K, V] { return [key, value];}
const p1 = pair<string, number>("age", 25);const p2 = pair("name", "Alice"); // InferredDefault Type Parameters
Section titled “Default Type Parameters”interface Response<T = any> { data: T; status: number;}
const res1: Response = { data: "anything", status: 200 };const res2: Response<User> = { data: user, status: 200 };