Challenge 2: Generics
- TypeScript course
- Intermediate
- Lesson 87/89
- 6 min
Solve a task using generics and constraints.
Generics challenge
In this challenge you will solve tasks that combine generic functions and constraints. You learned to define type parameters with <T>, add constraints with extends, and use keys with keyof. Generics preserve type safety while allowing code to work with any type.
Practice uzunluk generic function
Define a generic function named uzunluk: <T extends { length: number }>(x: T): number. Its body should be return x.length. Print the result of calling uzunluk("merhaba") with console.log.
Starter code
// uzunluk adinda generic fonksiyon
// T parametresi length ozelligi olanlarla sinirli
// x.length degerini dondur
// "merhaba" ile cagirSample solution
function uzunluk<T extends { length: number }>(x: T): number {
return x.length;
}
console.log(uzunluk("merhaba"));Expected output
7
Practice Field access with keyof
Define a generic function named al: <T, K extends keyof T>(obj: T, anahtar: K): T[K]. Its body should be return obj[anahtar]. The kisi object is { ad: "Ayşe", yas: 30 }. Print the result of calling al(kisi, "ad") with console.log.
Starter code
// al adinda generic fonksiyon
// iki tür parametresi T ve K
// K T'nin anahtarlarindan biri olsun
// obj[anahtar] degerini dondur
// kisi nesnesi tanimla
// al ile "ad" al ve yazdirSample solution
function al<T, K extends keyof T>(obj: T, anahtar: K): T[K] {
return obj[anahtar];
}
const kisi = { ad: "Ayşe", yas: 30 };
console.log(al(kisi, "ad"));Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used to require a generic type parameter to have a specific structure?
- readonly
- implements
- abstract
- extends constraint Correct answer
Explanation: The extends constraint requires the type parameter to have a specific structure or type; for example <T extends { length: number }>.
2 extends constraint
function uzunluk<T ____ { length: number }>(x: T): number {
return x.length;
}
function uzunluk<T extends { length: number }>(x: T): number {
return x.length;
}
Explanation: The extends keyword is used for generic constraints; implements is for classes, keyof is for keys.
3 Generic concepts
| Term | Meaning |
|---|---|
<T> |
Type parameter |
extends |
Constraint |
keyof |
Key set |
default |
Default type |