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?
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With