TypeScript Generics
Learn how to use TypeScript generics to create reusable and type-safe components, functions, and classes.
TypeScript Generics
Generics allow you to write flexible, reusable code while maintaining type safety. They let you create components that work with any type while still knowing what that type is.
Basic Generics
// Generic function
function identity(arg: T): T {
return arg;
}const num = identity(42); // number
const str = identity("hello"); // string
Generic Interfaces
interface Box {
value: T;
}const numberBox: Box = { value: 42 };
const stringBox: Box = { value: "hello" };
Generic Constraints
Limit what types can be used with constraints:
interface Lengthwise {
length: number;
}function logLength(arg: T): T {
console.log(arg.length);
return arg;
}
logLength("hello"); // Works - string has length
logLength([1, 2, 3]); // Works - array has length
logLength(42); // Error - number has no length
Generic Classes
class Storage {
private items: T[] = []; add(item: T): void {
this.items.push(item);
}
get(index: number): T | undefined {
return this.items[index];
}
getAll(): T[] {
return [...this.items];
}
}
const numberStorage = new Storage();
numberStorage.add(1);
numberStorage.add(2);
Multiple Type Parameters
function pair(key: K, value: V): [K, V] {
return [key, value];
}const userPair = pair("name", "John");
// [string, string]
Utility Types with Generics
// Partial - make all properties optional
interface User {
id: number;
name: string;
email: string;
}const partialUser: Partial = { name: "John" };
// Pick - select specific properties
type UserPreview = Pick;
// Omit - exclude specific properties
type UserWithoutEmail = Omit;
// Record - create object type
type UserRoles = Record;
What is the purpose of TypeScript generics?
React Hooks Deep Dive
SQL Joins Explained
Docker Fundamentals
REST API Design Best Practices
Git Advanced Techniques
Node.js Event Loop