typescript - 将元组解构为另一个元组类型不匹配

标签 typescript

据我所知,以下函数在输入方面似乎在逻辑上是合理的:

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/

相关文章:

angularjs - 将 Mongoose 模型表示为 Typescript 类

JavaScript( typescript /Angular ): Shortest/Fastest method to set object keys/values based on previous logic?

javascript - 带有区域限制的 Angular 8 拖放

ajax - 我如何使用 console.log 打印 JSON

javascript - Angular 2 - 日期选择器不起作用

typescript - 反射(reflect)元数据并查询装饰器的对象

typescript - 元组泛型

javascript - 如何修复错误 "Failed to compile : ./node_modules/@react-leaflet/core/esm/path.js 10:41 Module parse failed: Unexpected token (10:41)"

typescript - 通用函数和索引类型

typescript - 如何在 Typescript 中创建自定义事件?