Mastering TypeScript Generics
March 25, 2024
10 min read
TypeScriptWhat are Generics?
Generics allow you to write flexible, reusable code while maintaining type safety. They let you create components that work with a variety of types rather than a single type.
Basic Generic Syntax
Simple Generic Function
function identity<T>(arg: T): T {
return arg;
}
// Usage
const result = identity<string>("hello");
const number = identity<number>(42);
Generic Constraints
You can constrain generic types to specific types:
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
Advanced Patterns
Generic Interfaces
interface Container<T> {
value: T;
getValue(): T;
setValue(value: T): void;
}
Conditional Types
type IsString<T> = T extends string ? true : false;
// Usage
type A = IsString<"hello">; // true
type B = IsString<42>; // false
Practical Examples
Array Utilities
function getFirstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
function mapArray<T, U>(arr: T[], fn: (item: T) => U): U[] {
return arr.map(fn);
}
API Response Handling
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
const response = await fetch(url);
return response.json();
}
Best Practices
- Keep it simple - Don't over-generalize
- Document constraints - Make it clear what types are accepted
- Use meaningful names -
Tfor type,Kfor key,Vfor value - Test thoroughly - Generic code needs comprehensive testing
Conclusion
Generics are a powerful feature of TypeScript that enable you to write more flexible and maintainable code. Master them to take your TypeScript skills to the next level.
#typescript#generics#advanced#tutorial
Author
Kirtan Kalathiya
Full-stack developer passionate about creating exceptional web experiences. Sharing knowledge about web development, design, and technology.
← Previous Article
Building Scalable Node.js Applications
Next Article →
Building Modern Web Applications with Next.js 15
💬 Discussion
Share your thoughts and insights about this article. Have questions? Let's discuss in the comments.