Generics in TypeScript Explained

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

Jun 16, 2025 - 10:30
 0
Generics in TypeScript Explained

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!