【问题标题】:Typescript constructor shorthand when parameters are passed as object参数作为对象传递时的打字稿构造函数简写
【发布时间】:2021-09-15 09:47:05
【问题描述】:

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

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

  constructor(name: string, age: number) {
    this.name = name;
    this.age= age;
  }
}

所以这个类的等效简写构造函数符号将是

class Foo {
      constructor(private name: string, private age: number) {}
    }

同样,当构造函数参数作为如下对象传入时,我该如何做同样的速记。

    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;
      }
   }

【问题讨论】:

    标签: typescript typescript-typings typescript2.0


    【解决方案1】:

    我不知道有更短的方法。如果忽略构造函数,只是尝试将该对象分配给三个变量nameagegroup,那么这确实是一个关于如何在解构对象时声明类型的问题:

    const { name, age, group } = {
      name: 'name',
      age: 42,
      group: 'answers',
    };
    

    TypeScript 没有用于常规解构的特殊符号(许多 previous answersblog posts 最终使用与您相同的样式),因此它没有这样的解构符号在函数定义中。

    您可以通过将类型定义设为接口来使代码更简洁。

    【讨论】:

      【解决方案2】:

      你可以这样做:

        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);
      

      PlaygroundLink

      【讨论】:

      • @mohamed-imran 你的问题解决了吗?如果有问题请告诉我
      • 我喜欢这种方法。只是出于好奇,我如何在类中使用 this 关键字访问成员。是否有可能采用类似的方法?类似 this.name 而不是 this.obj.name
      • 是的,你可以。就像:this.obj.age
      • @AlirezaAhmadi 如果你在 obj 中有很多属性,你可以使用这个简写来避免在任何地方输入 thisconst { prop1, prop2, prop3, prop4 } = this.obj
      猜你喜欢
      • 2018-07-15
      • 1970-01-01
      • 2018-06-26
      • 2013-12-12
      • 2019-10-31
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多