gpt4 book ai didi

typescript - 对象内部的数组解构

转载 作者:搜寻专家 更新时间:2023-10-30 20:56:12 28 4
gpt4 key购买 nike

创建一个简单的数组并在(空)对象中解构它:

const foo: Array<number> = [1, 2, 3, 4];
const bar: Array<number> = {...foo};

类型检查不应该在这里失败吗? bar 在我看来不像是一个数组。编辑器根本没有提示并将 bar 视为数组类型,即使我可以在运行时轻松检查它不是。

编辑

Reproducing it easily in the TypeScript playground.

最佳答案

它看起来像是一个已知问题,因为 {...foo} 解构被编译到 Object.assign({}, foo)Object .assign() 声明为

assign<T, U>(target: T, source: U): T & U;

所以当第二个参数是数组时,结果与数组类型兼容。

希望它会在 better typing for Object.assign is implemented 时得到修复:

I am close to having a PR for spread types, so when those are in, Object.assign will change to have the correct type:

assign(target: T, source: U): { ...T, ...U }

如果实现正确,传播类型不应考虑不可枚举的属性,例如 length,因此您的代码将给出与

相同的错误
const p: Array<number> = {};

// Type '{}' is not assignable to type 'number[]'.
// Property 'length' is missing in type '{}'.

关于typescript - 对象内部的数组解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42926993/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com