Getting Started with TypeScript Generics
What Are Generics?
Generics allow you to create reusable components that can work with multiple types rather than a single one. They provide a way to make components "type-safe" without sacrificing flexibility.
Basic Syntax
function identity<T>(arg: T): T {
return arg;
}
const output = identity<string>("myString");Generic Interfaces
interface GenericIdentityFn<T> {
(arg: T): T;
}
function identity<T>(arg: T): T {
return arg;
}
const myIdentity: GenericIdentityFn<number> = identity;Generic Constraints
Sometimes you want to limit the types that can be passed to a generic function:
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): T {
console.log(arg.length);
return arg;
}Why Use Generics?
- Type safety at compile time
- Reusability without
any - Better IDE support with autocompletion
Generics are one of the most powerful features of TypeScript. Master them, and you'll write much more robust code.