What are Generics?
Generics are one of TypeScript's most powerful features, allowing you to write reusable, type-safe code that works with multiple types. Think of them as type-level functions — they take types as arguments and return new types.
Basic Syntax
The simplest generic is a function that returns whatever you pass in:
function identity<T>(arg: T): T {
return arg;
}
const num = identity(42); // T = number
const str = identity("hello"); // T = stringGeneric Constraints
You can restrict what types can be used with a generic using the extends keyword:
function getLength<T extends { length: number }>(arg: T): number {
return arg.length;
}
getLength("hello"); // OK — string has length
getLength([1, 2, 3]); // OK — array has length
getLength(42); // Error — number has no lengthGeneric Interfaces and Types
Generics shine when building reusable data structures:
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
type UserResponse = ApiResponse<User>;
type PostListResponse = ApiResponse<Post[]>;Conditional Types
Advanced TypeScript allows you to branch on type conditions:
type IsArray<T> = T extends any[] ? true : false;
type A = IsArray<number[]>; // true
type B = IsArray<string>; // falseMapped Types
Mapped types let you transform the properties of an existing type:
type Readonly<T> = {
readonly [K in keyof T]: T[K];
};
type Optional<T> = {
[K in keyof T]?: T[K];
};Conclusion
Generics unlock a new level of expressiveness in TypeScript. Start with simple generic functions, then gradually work up to conditional and mapped types as you need them.
Comments (0)
Sign in to join the conversation.
No comments yet. Be the first to share your thoughts.