Generics in TypeScript Explained
Generics allow you to create reusable, strongly-typed functions and types.
Simple Example
function identity<T>(arg: T): T { return arg; } const a = identity<number>(5); // a: number const b = identity<string>('hello'); // b: string
Generic on a Type
type ApiResponse<T> = { data: T; status: number; } const userResponse: ApiResponse<{id: number; name: string}> = { data: {id: 1, name: 'Alice'}, status: 200 };
Conclusion
Using generics lets you reuse code while keeping strong type safety!
Top comments (0)