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
AssignCtorfrom here, as shown in this playground link. It works because all you're doing is assigning the properties of the constructor argument to the instance. If that meets your needs I'll write an answer or close as a duplicate. If not, what am I missing?