Multiple type parameters
- TypeScript course
- Intermediate
- Lesson 18/89
- 4 min
Learn to take multiple type parameters.
More than one type parameter
A generic can take more than one type parameter. Types are separated by commas: <T, U>. Each parameter is independent and can be used anywhere in the signature. Order matters; the call must give types in the same order.
function cevir<T, U>(x: T, y: U): [U, T] {
return [y, x];
}
const r = cevir<number, string>(1, "a");
// r: [string, number]Key-value structures
Multiple type parameters are especially useful for key-value structures. A Map<K, V> maps a K key to a V value. You can write your own Cift<K, V> class to hold two values of different types together, type-safely.
Practice Key-value pair
Write a generic class Cift<K, V>. It should have private fields anahtar: K and deger: V; the constructor takes these values and assigns them to the fields. Method al(): [K, V] returns [this.anahtar, this.deger]. Then create a Cift<string, number> instance with "yas" and 25, and print the result of al().
Starter code
// Cift<K, V> sınıfını yaz
// private anahtar: K ve private deger: V alanları tanımla
// constructor bu değerleri alıp alanlara atasın
// al metodu [this.anahtar, this.deger] döndürsün
// Cift<string, number> örneği oluştur, al() yazdırSample solution
class Cift<K, V> {
private anahtar: K;
private deger: V;
constructor(anahtar: K, deger: V) {
this.anahtar = anahtar;
this.deger = deger;
}
al(): [K, V] {
return [this.anahtar, this.deger];
}
}
const c = new Cift<string, number>("yas", 25);
console.log(c.al());Expected output
[ 'yas', 25 ]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a generic with two type parameters declared?
- Two letters separated by semicolon, inside angle brackets
- Two letters separated by space, inside angle brackets
- Two letters inside angle brackets, separated by comma Correct answer
- Two letters inside square brackets, separated by comma
Explanation: Type parameters are written inside angle brackets, separated by commas.
2 Second type parameter
function esle<A, B>(a: A, b: ____): [A, B] { return [a, b]; }
function esle<A, B>(a: A, b: B): [A, B] { return [a, b]; }
Explanation: The second parameter must be of type B, so the type annotation is B. A is the wrong type, T is undefined, and string is a fixed type.
3 Multi type parameter parts
| Term | Meaning |
|---|---|
<T, U> |
Two type parameters |
<K, V> |
Type parameters for key-value |
[U, T] |
Reversing type order |
cevir<number, string> |
Two explicit type arguments |