您提到的手册链接涵盖了示例中的大多数场景解构 https://www.typescriptlang.org/docs/handbook/variable-declarations.html#object-destructuring,但我认为它涵盖的一种情况没有明确涵盖(只是隐含地)。
您所指的特定功能(我认为)是以下功能的组合:
您可以使用以下语法为对象中的其余项目创建变量...
:
and
您还可以为属性指定不同的名称:
手册没有给出两者都使用的示例,如下所示。这种组合使用的有趣之处在于...other
token 实际上并不意味着任何东西,并且永远不会被引用(或可引用)。在下面示例的“工作”版本中,如果没有错误行,则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
有一个提高与解构相关的剩余元素的使用清晰度的问题 https://github.com/Microsoft/TypeScript/issues/2713在底层语言规范中。