CodeBlanks Logo Icon CodeBlanks

Challenge 2: Generics

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

index.ts
// uzunluk adinda generic fonksiyon
// T parametresi length ozelligi olanlarla sinirli
// x.length degerini dondur
// "merhaba" ile cagir

Sample solution

index.ts
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

index.ts
// 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 yazdir

Sample solution

index.ts
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

Question
function uzunluk<T ____ { length: number }>(x: T): number {
  return x.length;
}
Answer
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

All lessons in Intermediate