据我所知,以下函数在输入方面似乎在逻辑上是合理的:
function testFunction<A,B,C,D> (a: A, more: [B, C, D]) : [A,B,C,D] {
return [a, ...more];
}
相反,Typescript 提示 ...more
,给出以下错误:
Type 'B | C | D' is not assignable to type 'B'.
Type 'C' is not assignable to type 'B'.
我是不是遗漏了什么,或者这是类型检查器的疏忽,可以安全地强制使用 return [a, ...more] as [A,B,C,D];
最佳答案
在应用扩展运算符时,类型检查器似乎确实将元组类型扩展为联合类型。观察:
const foo: [A, B] = ...
const bar = [...foo]; // inferred type (A | B)[]
我不确定这是设计使然还是只是当前实现的限制。我希望它实际上是后者,因为任何需要 T[]
的函数必须加宽[A, B]
至 (A | B)[]
适合类型参数 T
.
例如,无法生成 [A, B]
使用 Array.of
因为它的签名是T[] Array.of<T>(...items: T[])
:
Array.of(a, b); // Argument of type 'B' is not assignable to parameter of type 'A'.
Array.of<A | B>(a, b); // Fine, but inferred type (A | B)[]
Array.of(...[a, b]); // Fine, but inferred type (A | B)[]
解决这个问题的一种方法是简单地构造没有扩展运算符的结果数组:
function testFunction<A,B,C,D> (a: A, more: [B, C, D]) : [A,B,C,D] {
return [a, more[0], more[1], more[2]];
}
或者可能稍微更干净:
function testFunction<A,B,C,D> (a: A, [b, c, d]: [B, C, D]) : [A,B,C,D] {
return [a, b, c, d];
}
关于typescript - 将元组解构为另一个元组类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013392/