CodeBlanks Logo Icon CodeBlanks

Generic classes

Learn type-safe collections with generic classes.

Generic class definition

A generic class takes a type parameter in <T> right after the class name. The parameter can be used in all fields and methods. Each instance fixes the type, so a Kutu<string> only holds strings.

class Kutu<T> {
  private icerik: T;
  constructor(icerik: T) {
    this.icerik = icerik;
  }
  al(): T { return this.icerik; }
}
const k = new Kutu<string>("merhaba");
console.log(k.al());  // merhaba

Type-safe collections

Generic classes are ideal for writing type-safe collections. Stack, queue, tree structures can be written once as a generic class and used with any type. new Depo<number>() creates an instance that stores numbers, new Depo<string>() one that stores strings.

Practice Type-safe storage

Write a generic class Depo<T>. It should have a private field ogeler: T[] starting as an empty array. Method ekle(o: T): void pushes an item; method al(i: number): T returns the item at the given index. Then create a Depo<string> instance, add "elma", and print the result of al(0).

Starter code

index.ts
// Depo<T> sınıfını yaz
// private ogeler: T[] = []
// ekle metodu öge eklesin, al metodu indeksle döndürsün
// Depo<string> oluştur, "elma" ekle, al(0) yazdır

Sample solution

index.ts
class Depo<T> {
  private ogeler: T[] = [];
  ekle(o: T): void {
    this.ogeler.push(o);
  }
  al(i: number): T {
    return this.ogeler[i];
  }
}
const d = new Depo<string>();
d.ekle("elma");
console.log(d.al(0));

Expected output

elma

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Where is the type parameter written in a generic class?

  • Right after the class name, inside angle brackets Correct answer
  • At file top with a type T declaration
  • As a constructor parameter
  • After the method name

Explanation: In a generic class the type parameter is written inside angle brackets right after the class name.

2 Generic class instance

Question
class Kutu<T> {
  private deger: T;
  constructor(deger: T) { this.deger = deger; }
  al(): T { return this.deger; }
}
const k = new Kutu<____>(42);
Answer
class Kutu<T> {
  private deger: T;
  constructor(deger: T) { this.deger = deger; }
  al(): T { return this.deger; }
}
const k = new Kutu<number>(42);

Explanation: Since 42 is a number, the type argument must be number. string or boolean cause a compile error; T is undefined at the instantiation site.

3 Generic class parts

Term Meaning
class Kutu<T> Generic class declaration
new Kutu<number>(5) Generic class instance
private icerik: T Type parameter as field
al(): T Type parameter as return type

All lessons in Intermediate