英文:
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'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:
[{
"value": 10
}]
------------------------
{
"0": {
"value": 10
}
}
------------------------
{
"0": {
"value": 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 = { "0": {value: 10} }; // type check error, is correct
console.log(x);
x = { "0": {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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论