javascript - 打字稿:使用类中的默认值初始化对象
问题描述
如何创建一个使用默认属性初始化对象的打字稿类/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: ''
}
但理想情况下,我希望参数对于构造函数是可选的
解决方案
您可以使用可选参数,在您的代码中唯一缺少的是私人键盘:
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;
}
}
推荐阅读
- python - 基于日期时间索引构建列
- reactjs - 反应输入不输入
- javascript - 在父组件状态中存储回调时过时的关闭
- textfield - SwiftUI TextField 建议不带 textContentType 的 OTP 代码
- azure - 当 WEBSITE_RUN_FROM_PACKAGE 的内容发生变化时,如何重新启动 Azure 函数?
- ssl - 禁用 TLS1.2 密码套装 TLS_RSA_WITH_3DES_EDE_CBC_SHA 后,会话状态服务器不工作
- service - DDD:阻止外部服务调用和事件
- java - 在 Camunda 的 ExternalTaskClient 中启用 HTTPS
- c++ - 如何使用 Win32 API 显示“打开文件”弹出窗口
- c# - 是否可以通过 CosmosDB 在 Azure Function 中完美监控 Change Feed 的工作情况