Generics
Generic Constraints
Constraints let a generic function require the members it needs.
Generic Constraints
constraints.ts
interface HasLength {
length: number;
}
function lengthLabel<T extends HasLength>(value: T): string {
return `length=${value.length}`;
}
const word: string = ;
const label: string = lengthLabel<string>(word);
console.log(label);
interface HasLength {
length: number;
}
function lengthLabel<T extends HasLength>(value: T): string {
return `length=${value.length}`;
}
const word: string = ;
const label: string = lengthLabel<string>(word);
console.log(label);
interface HasLength {
length: number;
}
function lengthLabel<T extends HasLength>(value: T): string {
return `length=${value.length}`;
}
const word: string = ;
const label: string = lengthLabel<string>(word);
console.log(label);
generic constraint
A generic constraint such as `T extends HasLength` limits which values the generic function accepts.