How to Add Elements to a TypeScript Tuple Using Generics?

Starting with TypeScript v4, you can use variadic tuple types to spread generics in a tuple and add an arbitrary number of elements to it (that are yet to be defined).

For example:

// TS4+
type Foo<T extends unknown[]> = [string, ...T, number];

With this type, you now have the flexibility of defining the shape of the tuple by adding elements in place of the generic T:

type ex1 = Foo<[]>; // [string, number]
type ex2 = Foo<[boolean]>; // [string, boolean, number]
type ex3 = Foo<[number, string]>; // [string, number, string, number]
// ...

You may narrow the scope of the variadic tuples by extending the generic with a specific type. Consider for example the following type which only allows a subset of string values to be added:

// TS4+
type Foo<T extends string[]> = [string, ...T, number];

This type would only allow a subset of strings, anything else would throw an error:

// Error: Type '[number]' does not satisfy the constraint 'string[]'.
const ex: Foo<[number]> = ['foo', 1, 2];

The following shows a valid use of this type:

const ex: Foo<['foo', 'bar']> = ['a', 'foo', 'bar', 123];

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.