typescript / intermediate
Snippet
Transforming Argument Types with Tuple Mapped Types
Mapped tuple types transform the element types of a tuple array preserved in order, giving strong inference for functions accepting arrays of promises.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type PromiseTuple<T extends readonly unknown[]> = {[K in keyof T]: Promise<T[K]>;};async function awaitAll<T extends readonly unknown[]>(promises: [...PromiseTuple<T>]): Promise<T> {return Promise.all(promises) as Promise<any>;}async function main() {const [num, str] = await awaitAll([Promise.resolve(42),Promise.resolve('hello'),]);}
Breakdown
1
type PromiseTuple<T extends readonly unknown[]> = {
Defines a generic type taking a tuple T constrained to read-only arrays.
2
[K in keyof T]: Promise<T[K]>;
Maps over each index element in the tuple wrapping its value type into a Promise.
3
promises: [...PromiseTuple<T>]
Uses variadic tuple syntax to allow type inference of individual positional elements.
4
const [num, str] = await awaitAll([
Infers tuple type [number, string] for the unwrapped return value.