Generics
Generics let a function or type work with many types while staying safe. Write a type parameter in angle brackets. Constraints with extends limit what is allowed.
Example
function first<T>(items: T[]): T | undefined {
return items[0];
}
console.log(first([1, 2, 3]), first(["a", "b"]));
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longest("hello", "hi"));
interface Box<T> { value: T }
const b: Box<number> = { value: 5 };
console.log(b.value);Result
1 a hello 5
Exercise
Declare a type parameter.
function idT>(x: T): T { return x; }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.