What is the best way to design a TypeScript class or JavaScript object that initializes with default properties? I am currently using TypeScript classes with parameters as shown below:
Here is an example of my class:
export class StateModel {
stateID: number;
stateCode: string;
stateName: string;
stateTwoCharCode: string;
constructor(
stateId: number,
stateCode: string = '',
stateName: string = '',
stateTwoCharCode: string = ''){
this.stateID = stateId;
this.stateCode = stateCode;
this.stateName = stateName;
this.stateTwoCharCode = stateTwoCharCode;
}
}
When importing and using this class, I would like to be able to do something similar to:
let newClass = new StateModel();
If I were to log newClass
, I expect to see the following result:
newClass = {
stateCode: '',
stateName: '',
stateTwoCharCode: ''
}
However, I would prefer for the constructor parameters to be optional. Is there a way to achieve this?