Summary - Advanced generics
- TypeScript course
- Advanced
- Lesson 4/57
- 4 min
Write a concat helper with variadic tuples.
Summary - Advanced generics
In this group you learned advanced generic topics: variadic tuples provide variable-length type-safe tuples; tuple inference derives the tuple type from call arguments in generic functions; recursive generic types define self-referencing nested structures. Together they enable powerful, type-safe abstractions.
type Headed<T> = [string, ...T[]];
type Tree<T> = { value: T; left?: Tree<T> };Practice Write a concat helper
Define a generic type named Birlestir: <A extends unknown[], B extends unknown[]> = [...A, ...B]. Define function birlestir<A extends unknown[], B extends unknown[]>(a: A, b: B): Birlestir<A, B> whose body returns return [...a, ...b]. Assign the result of calling birlestir([1, 2], ["a", "b"]) to sonuc and print sonuc[2] with console.log.
Starter code
// Birlestir generic type tanimla
// iki tuple'i spread ile birlestiren fonksiyon yaz
// cagri sonucunu sonuc'a ata
// sonuc[2] yazdirSample solution
type Birlestir<A extends unknown[], B extends unknown[]> = [...A, ...B];
function birlestir<A extends unknown[], B extends unknown[]>(a: A, b: B): Birlestir<A, B> {
return [...a, ...b];
}
const sonuc = birlestir([1, 2], ["a", "b"]);
console.log(sonuc[2]);Expected output
a
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following is an example of a variadic tuple?
- [string, ...number[]] Correct answer
- number[]
- { a: number }
- [number, string]
Explanation: A variadic tuple is a tuple containing the spread operator; [string, ...number[]] is an example with a fixed head and a variable-length tail.
2 Recursive type self-reference
type Agac<T> = {
deger: T;
alt?: ____<T>;
};
type Agac<T> = {
deger: T;
alt?: Agac<T>;
};
Explanation: In a recursive type definition, the child field refers again to the same Agac<T> type.
3 Advanced generics summary
| Term | Meaning |
|---|---|
variadic tuple |
Variable-length tuple |
tuple inference |
Tuple from call |
recursive type |
Self-referencing type |
...T[] |
Spread tuple |