简体   繁体   English

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

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

I know we can make constructor short hand when we pass the parameters in a traditional way like我知道当我们以传统方式传递参数时,我们可以简化构造函数,例如

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

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

So the equivalent shorthand constructor notation for this class will be所以这个 class 的等效简写构造函数符号将是

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

Similarly, how can I do the same shorthand when the constructor parameters are passed in as objects like below.同样,当构造函数参数作为如下对象传入时,我该如何做同样的速记。

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

You can do like this:你可以这样做:

  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 PlaygroundLink

I am not aware of a shorter way.我不知道更短的方法。 If you ignore the constructors and just try to assign that object to three variables name , age , and group , then this is really a question about how to declare types while destructuring an object:如果您忽略构造函数并尝试将 object 分配给三个变量nameagegroup ,那么这确实是一个关于如何在解构 object 时声明类型的问题:

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

TypeScript does not have a special notation for regular destructuring (lots of previous answers and blog posts end up using the same style as you did), so it does not have such a notation for destructuring inside a function definition. TypeScript 没有用于常规解构的特殊符号(许多先前答案博客文章最终使用与您相同的样式),因此在 function 定义中没有用于解构的符号。

You can keep the code a little cleaner by making the type definition an interface .通过将类型定义设为接口,您可以使代码更简洁。

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

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