TypeScript
Beginner
1 min read
Generic Types, Interfaces, and Constraints
Example
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
timestamp: Date;
}
interface User { id: number; name: string; email: string }
interface Post { id: number; title: string; body: string }
type UserResponse = ApiResponse<User>;
type PostResponse = ApiResponse<Post>;
// Generic with multiple type parameters
interface KeyValuePair<K, V> {
key: K;
value: V;
}
// Generic function with keyof constraint
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
return keys.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {} as Pick<T, K>);
}
const user: User = { id: 1, name: "Alice", email: "alice@example.com" };
const partial = pick(user, ["name", "email"]); // { name, email }
// Generic class with constraint
interface Comparable<T> {
compareTo(other: T): number;
}
class SortedList<T extends Comparable<T>> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
this.items.sort((a, b) => a.compareTo(b));
}
toArray(): T[] { return [...this.items]; }
}
// Generic default type
type Nullable<T = string> = T | null;
const maybeStr: Nullable = null; // string | null
const maybeNum: Nullable<number> = 42; // number | null
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript