TypeScript
Beginner
1 min read
Generic Functions and Constraints
Example
// Simple generic function — identity
function identity<T>(value: T): T {
return value;
}
const n = identity(42); // T inferred as number
const s = identity("hello"); // T inferred as string
// Generic array utility
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const head = first([1, 2, 3]); // number | undefined
// Constraint with extends
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Alice", email: "alice@example.com" };
const userName = getProperty(user, "name"); // string
// getProperty(user, "missing"); // Error: not a key of user
// Constraint requiring a specific shape
interface HasLength { length: number }
function logLength<T extends HasLength>(value: T): T {
console.log(value.length);
return value;
}
logLength("hello"); // 5
logLength([1, 2, 3]); // 3
// Multiple type parameters
function zip<A, B>(a: A[], b: B[]): [A, B][] {
return a.map((item, i) => [item, b[i]]);
}
const zipped = zip([1, 2, 3], ["a", "b", "c"]);
// [[1,"a"], [2,"b"], [3,"c"]]
// Generic with default type
type Container<T = string> = { value: T };
const strBox: Container = { value: "hi" }; // T defaults to string
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