'spread argument union of tuples
I have function which returns union type of tuples. I want to pass it to function which accepts all its forms using spread operator ....
type TupleUnion = readonly [number, number] | readonly [number, number, string]
function getTuple() : TupleUnion
function calc(a, b, c?)
const tuple = getTuple();
calc(...tuple)
However on last line typescript compiler complains:
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
I do not want to redefine calc function. I need function getTuple to return union type which supports spread operator.
Solution 1:[1]
you can use variadic parameter to calc() function and passing the tuple into it
type TupleUnion = readonly [number, number] | readonly [number, number, string];
function getTuple(): TupleUnion
function calc(...a: TupleUnion)
const tuple = getTuple();
calc(...tuple);
Solution 2:[2]
The reason this is occurring is because the calc function has fixed parameters. However, tuple is an array which can change.
One way you can fix this is by declaring a type with tuple at its declaration (this is what the error is telling you to do):
const tuple: TupleUnion = getTuple();
Another way would be too to add the type to the calc function and remove the fixed parameters:
function calc(...args: TupleUnion)
You would then be able to access the contents of args with array syntax just like you would a tuple:
args[0]
A third way is to assert tuple as a constant, but this is hacky and should be considered if nothing else works:
const tuple = getTuple() as const;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | galih wisnuaji |
| Solution 2 |
