Back to blogs
Jane Smith

Understanding TypeScript Generics

Master TypeScript generics to write more flexible and reusable code.

TypeScript generics allow you to write flexible, reusable functions and classes that work with multiple types while maintaining type safety.

What Are Generics?

Generics provide a way to create components that work with any data type while still maintaining type information.

function identity<T>(arg: T): T {
  return arg;
}

// Usage
const result = identity<string>("hello"); // result is string
const num = identity(42); // num is inferred as number

Generic Constraints

You can constrain generics to specific shapes:

interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

logLength("hello"); // OK
logLength([1, 2, 3]); // OK
logLength({ length: 10 }); // OK

Generic Interfaces

Create flexible interfaces with generics:

interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

interface User {
  id: number;
  name: string;
}

const userResponse: ApiResponse<User> = {
  data: { id: 1, name: "John" },
  status: 200,
  message: "Success",
};

Conclusion

Generics are essential for writing scalable TypeScript code. They enable you to build reusable components without sacrificing type safety.