extends constraint
- TypeScript course
- Intermediate
- Lesson 20/89
- 4 min
Learn to constrain a type parameter with extends.
The extends constraint
With extends you put a bound on the type parameter. T extends Kisisel means T must have at least all members of Kisisel. Inside the body you can then access known properties like .ad through T; accessing an unknown property is a compile error.
interface Kisisel {
ad: string;
}
function yaz<T extends Kisisel>(x: T): void {
console.log(x.ad); // safe
}Why a bound matters
Without a constraint, you can only do things common to every type (e.g. assignment) on T; accessing .ad or .uzunluk is a compile error. Adding a bound lets the generic body safely use specific properties, improving reuse without losing type safety.
Practice Print the length
Define interface Uzunluklu as { uzunluk: number }. Write function uzunlukYaz<T extends Uzunluklu>(x: T): void that prints the length via console.log(x.uzunluk). Then call uzunlukYaz({ uzunluk: 7 }) to print the object's length.
Starter code
// Uzunluklu arayüzünü tanımla
// tek özellik: uzunluk, türü number
// uzunlukYaz fonksiyonunu generic olarak yaz
// T parametresine Uzunluklu kısıtı ekle
// console.log ile x'in uzunluk özelliğini yazdır
// { uzunluk: 7 } nesnesiyle fonksiyonu çağırSample solution
interface Uzunluklu {
uzunluk: number;
}
function uzunlukYaz<T extends Uzunluklu>(x: T): void {
console.log(x.uzunluk);
}
uzunlukYaz({ uzunluk: 7 });Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why can the function body access x.uzunluk?
interface Uzunluklu { uzunluk: number; }
function isle<T extends Uzunluklu>(x: T) {
return x.uzunluk;
}- T is bound via extends to Uzunluklu Correct answer
- T always becomes string
- Because any is used
- T can be any type
Explanation: Because of T extends Uzunluklu the compiler knows T has the uzunluk property. Without it the access would be a compile error.
2 Add the constraint
interface Adli { ad: string; }
function selamla<T ____ Adli>(x: T): string {
return "Merhaba " + x.ad;
}
interface Adli { ad: string; }
function selamla<T extends Adli>(x: T): string {
return "Merhaba " + x.ad;
}
Explanation: To bound a type parameter you use extends. implements is for classes; instanceof checks values; is is not a TypeScript keyword.
3 extends constraint parts
| Term | Meaning |
|---|---|
interface Adli |
Constraint type declaration |
T extends Adli |
Bound on the type parameter |
x.ad |
Safe access thanks to the bound |
yaz<Calisan>(...) |
Calling with a type satisfying the bound |