Generics in TypeScript Explained
xRdev_38

xRdev_38 @xrdev38

Joined:
Mar 15, 2022

Generics in TypeScript Explained

Publish Date: Jun 16
1 0

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!

Comments 0 total

    Add comment