如何创建一个Typescript类/ js来初始化具有默认属性的对象? 当前使用带有打字稿参数的类
例如这是我的课
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: ''
}
但理想情况下,我希望参数对于构造函数而言是可选的
答案 0 :(得分:0)
您可以使用可选的parameters,在您的代码中唯一缺少的是专用键盘:
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;
}
}
答案 1 :(得分:0)
您正在为可选参数编写代码。您只需要像这样启动它
text/plain
答案 2 :(得分:0)
如果我用打字稿写这个
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
显示了预期的对象结构