当参数作为对象传递时的 Typescript 构造函数简写

Moh*_*ran 14 typescript typescript-typings typescript2.0

我知道当我们以传统方式传递参数时,我们可以使构造函数简写

class Foo {
  
  private name: string;
  private age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age= age;
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,此类的等效简写构造函数符号将是

class Foo {
      constructor(private name: string, private age: number) {}
    }
Run Code Online (Sandbox Code Playgroud)

同样,当构造函数参数作为对象传递时,我该如何做相同的简写,如下所示。

    class Foo {
      private name: string;
      private age: number;
      private group: string;
      constructor({
        name,
        age,
        group,
      }: {
        name: string;
        age: number;
        group: string;
      }) {
        this.name= name;
        this.age= age;
        this.group= group;
      }
   }
Run Code Online (Sandbox Code Playgroud)

Ali*_*adi 14

你可以这样做:

  class Foo {
      constructor(public obj : { name: string, age: number, group: string}) {
      }
   }
  let foo = new Foo({name: 'name',  age: 42, group: 'answers'});

  alert(foo.obj.name);
Run Code Online (Sandbox Code Playgroud)

游乐场链接

  • @AlirezaAhmadi 如果你在 _obj_ 中有很多属性,你可以使用这个简写来避免到处使用 *this* 类型: `const { prop1, prop2, prop3, prop4 } = this.obj` (3认同)