【问题标题】:TypeScript imports vs. ES6 object destructuring [duplicate]TypeScript 导入与 ES6 对象解构 [重复]
【发布时间】:2017-06-17 17:19:41
【问题描述】:

使用 TS 导入,我相信我可以做到这一点:

import {foo as bar} from 'foo';

在 JS 或 TypeScript 中使用 ES6 对象解构 - 有没有办法以相同的方式重命名“导入的值”?

例如,

const {longVarName as lvn} = x.bar;

【问题讨论】:

  • const {longVarName:lvn} = x.bar;?将导致一个名为 lvn 的 const 具有 x.bar.longVarName 的值

标签: javascript node.js typescript typescript2.0 object-destructuring


【解决方案1】:

使用 Jaromanda X 建议的解决方案:

const {longVarName: lvn} = x.bar;

事实上,你可以做的不止这些:

多个变量

var {p: foo, q: bar} = o;

默认值:

var {a = 10, b = 5} = {a: 3};

嵌套对象:

const x = {a: {b: {c: 10}}};
const {a: {b: {c: ten}}} = x;
// ten === 10

欲了解更多信息,请参阅https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

【讨论】:

  • 这个 ES6 对吗?不是打字稿?
  • 是的,这是 ES6,正确的。
  • 我可以确认它也适用于 TypeScript,这是有道理的,因为 TS 在某种程度上紧跟 ES6。
猜你喜欢
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
相关资源
最近更新 更多