Summary - Generics
- TypeScript course
- Intermediate
- Lesson 19/89
- 4 min
Write a type-safe store class with generics.
Summary - Generics
Generics let a single piece of code work with different types type-safely by parameterizing the type. Generic functions are written as function ad<T>, generic classes as class Ad<T>. Multiple type parameters are also possible: <K, V>. Combining these three forms, you can build type-safe stores, mappers, and collections.
class Eslestirme<K, V> {
private veri: [K, V][] = [];
koy(k: K, v: V) { this.veri.push([k, v]); }
}Practice Type-safe mapper
Write a generic class Eslestirme<K, V>. It should have a private field veri: [K, V][] starting as an empty array. Method koy(k: K, v: V): void pushes the pair. Method al(k: K): V | undefined returns the matching value, or undefined. Then create an Eslestirme<string, number>, add "a"->1 and "b"->2, and print al("a") and al("b") on separate lines.
Starter code
// Eslestirme<K, V> sınıfını yaz
// veri alanı [K, V][] türünde olsun
// koy metodu anahtar ve değer eklesin
// al metodu anahtara göre değer döndürsün
// Eslestirme<string, number> oluştur, "a"->1, "b"->2 ekle
// al("a") ve al("b") sonuçlarını ayrı satırlarda yazdırSample solution
class Eslestirme<K, V> {
private veri: [K, V][] = [];
koy(k: K, v: V): void {
this.veri.push([k, v]);
}
al(k: K): V | undefined {
for (let i = 0; i < this.veri.length; i++) {
if (this.veri[i][0] === k) return this.veri[i][1];
}
return undefined;
}
}
const e = new Eslestirme<string, number>();
e.koy("a", 1);
e.koy("b", 2);
console.log(e.al("a"));
console.log(e.al("b"));Expected output
1 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main benefit of generics?
- Type-safe reusable code Correct answer
- Faster execution
- Shorter variable names
- Less memory usage
Explanation: Generics let the same code work type-safely with different types. They have nothing to do with speed or memory.
2 Two-type-parameter store
class Tablo<K, V> {
private satirlar: [K, V][] = [];
ekle(k: K, v: V) {
this.satirlar.push([____]);
}
}
class Tablo<K, V> {
private satirlar: [K, V][] = [];
ekle(k: K, v: V) {
this.satirlar.push([k, v]);
}
}
Explanation: Since the array expects a [K, V] tuple, the correct order is k, v. v, k is the wrong order; K, V are type names (not values); k is a single value.
3 Match generic structures
| Term | Meaning |
|---|---|
function ad<T>(...) |
Generic function |
class Ad<T> {...} |
Generic class |
<T, U> |
Multiple type parameters |
new Ad<number>() |
Instantiation with type argument |