繁体   English   中英

Typescript 参数作为 object 传递时的构造函数简写

[英]Typescript constructor shorthand when parameters are passed as an object

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

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

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

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

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

你可以这样做:

  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

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

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

TypeScript 没有用于常规解构的特殊符号(许多先前答案博客文章最终使用与您相同的样式),因此在 function 定义中没有用于解构的符号。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM