15

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 2

15

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

Sign up to request clarification or add additional context in comments.

3 Comments

I like this approach. Just out of curiosity, how I could access the members using this keyword inside the class. Is it possible with a similar approach? Something like this.name instead of this.obj.name
Yes you can. just like : this.obj.age
@AlirezaAhmadi if you have a lot of properties in obj you may use this shorthand to avoid type this everywhere: const { prop1, prop2, prop3, prop4 } = this.obj
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.