Generics
Generic Constraints
Constraints let a generic function require the members it needs.
generic constraint
A generic constraint such as `T extends HasLength` limits which values the generic function accepts.
Generic Constraints
constraints.ts
Replay: real traced execution (multi-file project)
interface HasLength {
length: number;
}
function lengthLabel<T extends HasLength>(value: T): string {
return `length=${value.length}`;
}
const word: string = "generic";
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 = "type";
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 = "constraint";
const label: string = lengthLabel<string>(word);
console.log(label);
word ← generic
6 return `length=${value.length}`;7}89const word→ generic: string = "generic"; //@word="type", "constraint"10const label: string = lengthLabel<string>(wordgeneric);function lengthLabel<T extends HasLength>(value: T): string
2 length: number;3}45function lengthLabel<T extends HasLength>(valuegeneric: T): string {6 return `length=${value.length7}`;7}label ← length=7
9const word: string = "generic"; //@word="type", "constraint"10const label→ length=7: string = lengthLabel<string>(wordgeneric);1112console.log(labellength=7);outputlength=7
word ← type
6 return `length=${value.length}`;7}89const word→ type: string = "type";10const label: string = lengthLabel<string>(wordtype);function lengthLabel<T extends HasLength>(value: T): string
2 length: number;3}45function lengthLabel<T extends HasLength>(valuetype: T): string {6 return `length=${value.length4}`;7}label ← length=4
9const word: string = "type";10const label→ length=4: string = lengthLabel<string>(wordtype);1112console.log(labellength=4);outputlength=4
word ← constraint
6 return `length=${value.length}`;7}89const word→ constraint: string = "constraint";10const label: string = lengthLabel<string>(wordconstraint);function lengthLabel<T extends HasLength>(value: T): string
2 length: number;3}45function lengthLabel<T extends HasLength>(valueconstraint: T): string {6 return `length=${value.length10}`;7}label ← length=10
9const word: string = "constraint";10const label→ length=10: string = lengthLabel<string>(wordconstraint);1112console.log(labellength=10);outputlength=10
Follow the Length
wordstarts asgeneric.lengthLabel<string>(word)receives that string.- The function reads
value.length. generichas7letters.- The program prints
length=7. | word | value.length | printed output | | --- | ---: | --- | | generic | 7 | length=7 | | type | 4 | length=4 | | constraint | 10 | length=10 |
Exercise: constraints.ts
Reproduce length=7, then use word type and constraint to predict length=4 and length=10.