Typescript constructor shorthand when parameters are passed as an object

Viewed 3633

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

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.

Related