DEV Community

xRdev_38
xRdev_38

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using generics lets you reuse code while keeping strong type safety!

Top comments (0)