TypeScript Generic Constraints
A generic constraint is a rule that limits what a placeholder type may be. The rule is written with extends after the placeholder.
A length constraint
longest accepts only values with a length property. Strings and arrays both have one.
function longest<T extends { length: number }>(value: T): T {
return value;
}
console.log(longest("hello").length);
console.log(longest([1, 2, 3]).length);A value with no length
A number has no length property. The compiler refuses the call.
function longest<T extends { length: number }>(value: T): T {
return value;
}
console.log(longest(42));A constraint to a union
combine accepts a string or a number for T. Both arguments must use the same member.
function combine<T extends string | number>(a: T, b: T): T[] {
return [a, b];
}
console.log(combine("a", "b"));
console.log(combine(1, 2));Example
function longest<T extends { length: number }>(value: T): T {
return value;
}
const word = longest("typescript");
const list = longest([4, 8, 15, 16]);
console.log(word);
console.log(word.length);
console.log(list.length);Key points
- A constraint is written after the placeholder with extends.
- Only types that meet the rule can fill the placeholder.
- A type with a numeric length property meets the length rule.
- A plain number has no length property.
- A constraint can name a union of allowed types.
In this example, longest receives a string and then an array. Both values have a length property, so both calls pass the constraint. The program logs the word and the two lengths.
Note
A constraint checks the shape a type must have. It does not change the value at runtime.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does a generic constraint do?