Typescript 构造函数 shorthand 当参数作为对象传递时

Typescript constructor shorthand when parameters are passed as object

我知道当我们以像

这样的传统方式传递参数时,我们可以简化构造函数
class Foo {
  
  private name: string;
  private age: number;

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

所以这个 class 的等效 shorthand 构造函数符号将是

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

类似地,当构造函数参数作为对象传入时,我如何做同样的事情shorthand。

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

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

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

TypeScript 没有用于常规解构的特殊符号(很多 and blog posts 最终使用与您相同的样式),因此它没有用于函数定义内部解构的符号。

您可以通过将类型定义设为接口

使代码更简洁一些

你可以这样做:

  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