TypeScript 数组扩展运算符类型安全

huangapple go评论61阅读模式
英文:

Typescript array spread operator type safety

问题

我有一段相对简单的代码我不知道为什么这不会产生任何错误

```js
interface ITest {
  value: number;
};

let x: ITest[] = [{ value: 10 }];
console.log(x);

x = { ...x };
console.log(x);

x = { ...[{ value: 10 }] };
console.log(x);

这会产生以下结果:

[{
  "value": 10
}]
------------------------
{
  "0": {
    "value": 10
  }
}
------------------------
{
  "0": {
    "value": 10
  }
}

第二和第三次对 x 的赋值明显不是类型 ITest[]
我认为这与展开运算符有关,或者与 {} 内部的 [] 创建了某种奇怪的映射类型有关。

这是如何工作的?
TS Playground


<details>
<summary>英文:</summary>

I have a relatively simple piece of code, and I don&#39;t know why this does not produce any errors:

```js
interface ITest {
  value: number;
};

let x: ITest[] = [{  value: 10 }];
console.log(x);

x = { ...x };
console.log(x);

x = { ...[{value: 10}] }
console.log(x);

which produces:

[{
  &quot;value&quot;: 10
}] 
------------------------
{
  &quot;0&quot;: {
    &quot;value&quot;: 10
  }
} 
------------------------
{
  &quot;0&quot;: {
    &quot;value&quot;: 10
  }
} 

The second and third assignment to x are clearly not of type ITest[].
I think it has to do with the spread operator or with the fact that [] inside the {} creates some sort of weird mapping type.

How does this work?
TS Playground

答案1

得分: 1

这实际上似乎是类型检查器在一个边缘情况下的错误。不知何故,如果使用扩展运算符且内部类型正确,则类型检查器无法意识到外部数组的不匹配类型。
此外,以下示例显示在其他情况下它可以正常工作:TS Playground

x = { "0": {value: 10} };  // 类型检查错误,正确
console.log(x);

x = { "0": {value: 10}, ...[] };  // 没有类型检查错误,但是是一个对象而不是一个数组
console.log(x);

x = [ {value: 10} ];  // 没有类型检查错误,正确
console.log(x);

更新

这是一个已知的 GitHub 问题(在问题的初始陈述中不太清楚,但在后来的评论中有多个关于这种行为的描述)。

英文:

This actually seems to be an error of the type checker on an edge case. Somehow the type checker does not realise the mismatching type of the outer array if the spread operator is used and the inner type is correct.
Also the following examples show that it works under other circumstances correctly: TS Playground

x = { &quot;0&quot;: {value: 10} };  // type check error, is correct
console.log(x);

x = { &quot;0&quot;: {value: 10}, ...[] };  // no type check error, but is an object instead of an array
console.log(x);

x = [ {value: 10} ];  //  no type check error, is correct
console.log(x);

Update

This is a known issue on github (it is not quite clear at the initial statements of the issue but further down there are multiple accounts of this behavior.)

huangapple
  • 本文由 发表于 2023年7月13日 21:20:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定