Is there any way to assign property values to the element of the class by default, if they are omitted by the user?
I have a custom class that contains an optional instance of another class:
export class MyClass1 {
constructor() {
this.name = "";
this.classInstance = new MyClass2();
}
name: string;
classInstance?: MyClass2;
}
class MyClass2 {
constructor() {
this.name = "MyClass2 initial name";
}
name: string;
}
The content for MyClass1 comes from JSON, so sometimes the class variable member classInstance can be undefined. In these cases, I would like the constructor MyClass1 to initiate a new variable MyClass2 () into the member variable of the class.
Here is how I can create an instance of MyClass1:
let myNewClass: MyClass1 = {
name: "MyClass"
}
Instance , , . , . classInstance, , MyClass1. , , ( , ):
let myNewClass: MyClass1 = {
name: "MyClass"
} as MyClass1
classInstance , , null/ undefined.
, ( ), .