gpt4 book ai didi

javascript - 在 TypeScript 中解构对象时重命名剩余的属性变量

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:27 27 4
gpt4 key购买 nike

EDIT:

I opened an issue related to this on github: https://github.com/Microsoft/TypeScript/issues/21265
It seems that { ...other: xother } is not valid JS, neither TS, code and it should not even compile.

原始问题:

让我们假设以下示例:

const values = { a: "1", b: "2", c: "3", d: "4" };
const { a: va, b: vb, ...other } = values;

其中为属性 a 分配了一个新的变量名称 va

根据 TypeScript 规范,对其余属性 ...other 执行相同操作是否有效?像这样的东西:

const { a: va, b: vb, ...other: vother } = values;

我知道它有效,我已经测试过它 ( online test )。但是我无法找到它的定义位置。

引用属性重命名的文档示例始终显示“正常”情况:TypeScript Handbook - Variable Declarations .规范语法引用了规范中未描述(或我遗漏)的 BindingPattern:TypeScript Spec .

我的第一印象是它不是很有用,因为 ...other 已经是一个自定义变量名。但它有效。而且我很想知道它具体定义在哪里,或者它是否只是一个有效的极端情况(我想不是)。

最佳答案

您提到的手册链接涵盖了您在 destructuring 下的示例中的大部分场景。 ,但我认为它涵盖的一种情况并未明确涵盖(仅隐含)。

您所指的特定功能(我认为)是以下各项的组合:

You can create a variable for the remaining items in an object using the syntax ...:

You can also give different names to properties:

手册中没有给出两者都使用的示例,如下所示。这种组合使用的有趣部分是 ...other 标记实际上没有任何意义,并且从未被引用(或可引用)。在下面示例的“工作”版本中,没有错误行,other 标记根本不会出现在输出中。

这里是简化的例子:

const values = { a: "1", b: "2", c: "3", d: "4" };

const { a: one, ...other: twoThreeFour } = values;

console.log(other); // ERROR there is no variable 'other'
console.log(a, twoThreeFour); // OK

并且没有错误的版本 - 转译后的 JavaScript 在代码中的任何地方都没有引用 other:

const values = { a: "1", b: "2", c: "3", d: "4" };

const { a: one, ...other: twoThreeFour } = values;

console.log(a, twoThreeFour); // OK

有一个issue to improve the clarity of the use of rest elements in relation to destructuring在底层语言规范中。

关于javascript - 在 TypeScript 中解构对象时重命名剩余的属性变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48318640/

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