snippettypescriptModeratepending
TypeScript generics with constraints and defaults
Viewed 0 times
genericsconstraintsextendskeyofinferdefault type
Problem
Need to write generic functions and types that are flexible but type-safe with proper constraints.
Solution
Generic patterns from simple to advanced:
// Basic generic with constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// Generic with default type
type ApiResponse<T = unknown> = {
data: T;
status: number;
error?: string;
};
// Constrained generic for serializable data
function serialize<T extends Record<string, unknown>>(data: T): string {
return JSON.stringify(data);
}
// Generic factory pattern
function createStore<T>(initialValue: T) {
let value = initialValue;
return {
get: (): T => value,
set: (newValue: T) => { value = newValue; },
update: (fn: (current: T) => T) => { value = fn(value); },
};
}
// Multiple constraints with intersection
function merge<T extends object, U extends object>(a: T, b: U): T & U {
return { ...a, ...b };
}
// Infer return type of a function
type AsyncReturnType<T extends (...args: any[]) => Promise<any>> =
T extends (...args: any[]) => Promise<infer R> ? R : never;
// Usage
type UserData = AsyncReturnType<typeof fetchUser>; // Inferred!Why
Generics with constraints catch type errors at compile time while maintaining flexibility. Defaults reduce boilerplate for common cases.
Context
TypeScript libraries and utility functions
Revisions (0)
No revisions yet.