Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly create a tuple in Typescript

Tags:

typescript

Is there a way without type hinting to create a tuple in Typescript.

If I simply do

const tuple = [1, 2];

the type of Tuple number[]

The closest I can get to a oneliner is

const tuple: [number, number] = [1, 2];

Am I missing something, or is this the only way?

like image 652
Jay Wick Avatar asked Apr 09 '18 09:04

Jay Wick


2 Answers

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]
like image 198
Guillaume Avatar answered Sep 21 '22 21:09

Guillaume


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]
like image 20
Titian Cernicova-Dragomir Avatar answered Sep 19 '22 21:09

Titian Cernicova-Dragomir