我有返回元组联合类型的函数。我想将它传递给使用扩展运算符
...
接受其所有形式的函数。
type TupleUnion = readonly [number, number] | readonly [number, number, string]
function getTuple() : TupleUnion
function calc(a, b, c?)
const tuple = getTuple();
calc(...tuple)
但是在最后一行打字稿编译器抱怨:
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
我不想重新定义
calc
函数。我需要函数 getTuple 返回支持扩展运算符的联合类型。
您可以使用可变参数到
calc()
函数并将元组传递给它
type TupleUnion = readonly [number, number] | readonly [number, number, string];
function getTuple(): TupleUnion
function calc(...a: TupleUnion)
const tuple = getTuple();
calc(...tuple);
发生这种情况的原因是因为
calc
函数具有固定参数。然而,tuple
是一个可以改变的数组。
解决此问题的一种方法是在其声明中声明带有
tuple
的类型(这是错误告诉您要做的事情):
const tuple: TupleUnion = getTuple();
另一种方法是将类型添加到
calc
函数并删除固定参数:
function calc(...args: TupleUnion)
然后您就可以使用数组语法访问
args
的内容,就像访问元组一样:
args[0]
第三种方法是将
tuple
断言为常量,但这很麻烦,如果没有其他方法,应该考虑:
const tuple = getTuple() as const;
这是一个已知的当前限制/问题。有一个与此问题相关的未决问题: https://github.com/microsoft/TypeScript/issues/49802。