Is there a way to automatically set default values for class member properties if the user does not provide them?
I have created a customized class that includes an optional instance of another class:
export class MyClass1 {
constructor() {
this.name = "";
this.classInstance = new MyClass2();
}
name: string; // object's name
classInstance?: MyClass2;
}
class MyClass2 {
constructor() {
this.name = "MyClass2 initial name";
}
name: string;
}
The data for MyClass1 is sourced from JSON, which means that sometimes the classInstance property can be undefined. In such cases, I want the MyClass1 constructor to assign new MyClass2() to the classInstance property by default.
This is how I create an instance of MyClass1:
let myNewClass: MyClass1 = {
name: "MyClass"
}
Despite omitting the classInstance, I assumed that it would still take on the default value specified in the constructor. However, this was not the case. I even attempted removing the optional sign from the classInstance property, but encountered a compilation error because then the object had to match the structure of MyClass1. Although I tried casting to avoid errors, the issue persisted (and I'm unsure if the casting was done correctly):
let myNewClass: MyClass1 = {
name: "MyClass"
} as MyClass1
In both scenarios, the classInstance did not receive the default value set in the constructor; it remained null/undefined.
For me, solving the casting dilemma or modifying the properties to be optional is acceptable as long as I can control the default values.