Typescript:使用类中的默认值初始化对象



如何创建一个用默认属性初始化对象的typescript class/js?当前正在使用具有typescript参数的类

这是我的

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;
}
}

在我导入它的代码中,我想调用这样的东西:

let newClass = new StateModel();

如果我控制台日志newClass,我希望得到以下结果:

newClass = {
stateCode: '',
stateName: '',
stateTwoCharCode: ''
}

但理想情况下,我希望参数对构造函数来说是可选的

您可以使用可选参数,在您的代码中,唯一缺少的是专用键盘:

export class StateModel {
stateID: number;
stateCode: string;
stateName: string;
stateTwoCharCode: string;
constructor(
stateId: number, 
private stateCode: string = '', 
private stateName: string = '',
private stateTwoCharCode: string = ''){
this.stateID = stateId;
this.stateCode = stateCode;
this.stateName = stateName;
this.stateTwoCharCode = stateTwoCharCode;
}
}

可选参数的代码正在工作。你只需要像这个一样启动它

newClass: StateModel = new StateModel(1);

https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=11&pc=32#代码/KYDwDg9gTgLgBAYwDYEMDOa4GUYpsAWQgBNgk4BvAKDkQgDs0YoBXBGaAChtrjBYBGSAJYI4TPMACSxAFxx6LALYDgUADRwetfkNHjc+AMLg8plGH0A5nAC8AOSPN2vpYBukg5IByKJTMDSxt7Jxc3ME9vCXwAFQB3CCMACxQoE1JzZitbB2cASmoeAF8qMqoebiY4ADMICD6YATsQ0JTJE4ARgAmAGYCoA

如果我用打字稿写这个

export class StateModel {
constructor(
public stateId: number, 
public stateCode: string = '', 
private stateName: string = '',
private stateTwoCharCode: string = ''){
}
}
const foo = new StateModel(123)
console.log(foo,"foo")

它在javascript 中编译成这个

export class StateModel {
constructor(stateId, stateCode = '', stateName = '', stateTwoCharCode = '') {
this.stateId = stateId;
this.stateCode = stateCode;
this.stateName = stateName;
this.stateTwoCharCode = stateTwoCharCode;
}
}
const foo = new StateModel(123);

日志foo显示了预期的对象结构