Implicitly create a tuple in Typescript

With typescript 3.0, you can have your own utility function:

const tuple = <T extends any[]>(...args: T): T => args

And use it this way:

const tup = tuple(1, 2) // tup type is [number, number]

As of TypeScript 3.4, you can add simply as const at the end.

const tuple = [1, 2] as const;

Full credit to @bela53's answer, which has a better example and link to TS playground.


Typescript will not infer tuple types from array literals. You can specify the type explicitly, as you have, or you can create a helper function to make it a bit easier and still get some inference.

const tuple = <T extends [any] | any[]>(args: T): T => args
tuple(["A", "B"]) // [string, string]

Edit

Starting from 3.4 you can also use an as const assertion. This does have the advantage of not needing the extra function but it will generate a read-only tuple:

var t = [1, ''] as const;
t[0] = 1  //err

Starting from 3.0 you can also sue tuples in rest parameter to infer tuples:

const tuple = <T extends any[]>(...args: T): T => args
tuple("A", "B") // [string, string]

Tags:

Typescript