If we define "elegant" as having a DRY syntax, then there is little room for improvement. The example below demonstrates how you can streamline the constructor body implementation by utilizing default parameters and a self-referential type modified by the Partial utility:
TS Playground
class Person {
age: number;
name: string;
constructor({ age = 0, name = "" }: Partial<Person> = {}) {
this.age = age;
this.name = name;
}
}
console.log(new Person({ name: "Pete" })); // { age: 0, name: "Pete" }
console.log(new Person({ age: 155 })); // { age: 155, name: "" }
console.log(new Person({ age: 155, name: "Pete" })); // { age: 155, name: "Pete" }
console.log(new Person({})); // { age: 0, name: "" }
console.log(new Person()); // { age: 0, name: "" }
TypeScript also offers parameter properties. However, this concept does not apply to the given example because the single constructor parameter is an object type, which cannot be assigned to any members of the class itself. By restructuring the class constructor to use ordered parameters for each field (instead of an object parameter), you could make use of this syntax pattern.