Variadic tuples
- TypeScript course
- Advanced
- Lesson 1/57
- 4 min
Learn variadic tuple types.
What is a variadic tuple?
A variadic tuple is a variable-length tuple whose last element can be spread with the ... operator. It is written as [A, ...B[]]. This way the leading elements are fixed while the rest are flexible in count. It is especially used to extend function parameters type-safely.
type Headed<T> = [string, ...T[]];
const x: Headed<number> = ["title", 1, 2, 3];Concatenation with tuple spread
To concatenate two tuples, the form [...A, ...B] is used, where A and B are tuple types. Unlike array concatenation, this preserves the element types. For example, merging [number, ...string[]] with [boolean] yields [number, ...string[], boolean].
type Concat<A extends unknown[], B extends unknown[]> = [...A, ...B];Practice Write a headed tuple
Define a generic type named Baslikli: <T> = [string, ...T[]]. The y variable should be of type Baslikli<number> with value ["baslik", 1, 2]. Print the first element with y[0] using console.log.
Starter code
// Baslikli adinda generic tuple turunu tanimla
// başta bir string, ardından istenen sayıda T elemanı olsun
// y degiskenini number elemanlariyla tanimla
// y[0] yazdirSample solution
type Baslikli<T> = [string, ...T[]];
const y: Baslikli<number> = ["baslik", 1, 2];
console.log(y[0]);Expected output
baslik
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which part of a variadic tuple takes the spread operator?
- Every element
- No spread operator used
- The first element
- The last element Correct answer
Explanation: In a variadic tuple the spread operator is used on the last element; this keeps the leading elements fixed and the rest flexible in count.
2 Spread operator
type Baslikli<T> = [string, ____ T[]];
type Baslikli<T> = [string, ... T[]];
Explanation: In a variadic tuple the spread operator is written as ...; this allows the last element to have a flexible count.
3 Variadic tuple concepts
| Term | Meaning |
|---|---|
... |
Spread operator |
[A, ...B[]] |
Variadic tuple form |
son eleman |
Spread here |
[...A, ...B] |
Tuple concatenation |