简体   繁体   中英

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

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:

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.

You can keep the code a little cleaner by making the type definition an interface .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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