【问题标题】:Is it possible to destructure a property out of the object and assign it to a property on the constructor?是否可以从对象中解构属性并将其分配给构造函数上的属性?
【发布时间】:2017-10-20 20:14:42
【问题描述】:

我正在使用打字稿并想从对象中解构属性。问题是我需要将它分配给类的构造函数上的一个属性:

var someData = [{title: 'some title', desc: 'some desc'}];
var [{title}] = someData; // 'some title';

我想要类似的东西:

var [{title :as this.title$}] = someData;

这可能以任何形式或形式出现吗?

【问题讨论】:

    标签: javascript typescript destructuring


    【解决方案1】:

    是的,您可以这样做,但是您需要删除声明符 (var),因为您正在解构为已经存在的东西。此外,as 是无效语法。删除它。

    [{title: this.title$}] = someData;
    

    一个完整的例子:

    const someData = [
      { title: 'Destructuring' }
    ];
    
    class A {
      title$: string;
      constructor() {
        [{ title: this.title$ }] = someData;
      }
    }
    

    TypeScript playground

    Babel REPL

    通过堆栈片段

    const someData = [{
      title: 'Destructuring'
    }];
    
    class A {
      constructor() {
        [{title: this.title$}] = someData;
      }
    }
    
    console.log(new A());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 2010-11-17
      • 2019-01-31
      相关资源
      最近更新 更多