Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
      }
   }
like image 471
Mohamed Imran Avatar asked Jan 27 '26 14:01

Mohamed Imran


1 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

like image 113
Alireza Ahmadi Avatar answered Jan 31 '26 16:01

Alireza Ahmadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!