4 min read
•Question 43 of 48hardWhat are Variadic Tuple Types?
Spreading and manipulating tuples.
What You'll Learn
- Tuple spread syntax
- Rest elements
- Practical patterns
Tuple Spreading
code.tsTypeScript
type Tuple1 = [string, number];
type Tuple2 = [boolean, ...Tuple1];
// [boolean, string, number]
type Tuple3 = [...Tuple1, boolean];
// [string, number, boolean]Generic Concatenation
code.tsTypeScript
type Concat<T extends unknown[], U extends unknown[]> = [...T, ...U];
type Result = Concat<[1, 2], [3, 4]>;
// [1, 2, 3, 4]Rest Elements
code.tsTypeScript
type StringAndRest = [string, ...number[]];
const a: StringAndRest = ["hello"]; // OK
const b: StringAndRest = ["hello", 1, 2, 3]; // OK
// Function with variadic args
function concat<T extends unknown[], U extends unknown[]>(
arr1: [...T],
arr2: [...U]
): [...T, ...U] {
return [...arr1, ...arr2];
}
const result = concat([1, 2], ["a", "b"]);
// Type: [number, number, string, string]Head and Tail
code.tsTypeScript
type Head<T extends unknown[]> = T extends [infer H, ...unknown[]] ? H : never;
type Tail<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never;
type H = Head<[1, 2, 3]>; // 1
type T = Tail<[1, 2, 3]>; // [2, 3]