typescriptobject-destructuringtypescript-class

Typescript constructor shorthand for named parameters


It's been a while since the constructor shorthand was introduced, and it's really useful. Now I can write this:

class Dog {
  constructor(
    public age: number,
    public weight: number,
  ) {}
}

instead of this:

class Dog {
  public age: number
  public weight: number

  constructor(
    age: number,
    weight: number,
  ) {
    this.age = age
    this.weight = weight
  }
}

And it works even better for more complex classes.

I wonder if there is some shorthand for class constructor with named parameters (using object destructing)? I think new Dog({age: 3, weight: 8}) is much clearer than new Dog(3, 8). No chance of misplacing the argument positions. But class definition for it looks really ugly:

class Dog {
  // 1. declare properties
  public age: number
  public weight: number

  constructor({
    // 2. object destructing
    age,
    weight,
  }: {
    // 3. declare object type
    age: number,
    weight: number,
  }) {
    // 4. assign values
    this.age = age
    this.weight = weight
  }
}
// x4 duplicates, no DRY at all

Solution

  • There's no syntax for that but you could make some DRY by introducing an interface and merge it into the class:

    Playground

    interface DogProps {
        age: number,
        weight: number,
    }
    interface Dog extends DogProps {}
    class Dog {
        constructor(props: DogProps){
            Object.assign(this, props);
        }
        feed(){
            console.log('Thank you, my Snack Lord');
        }
    }
    
    const dog = new Dog({age: 3, weight: 20});
    dog.age // number