typescripttypescript-typingstypescript2.0

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

Solution

  • 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