首页 > 解决方案 > 打字稿:使用类中的默认值初始化对象

问题描述

如何创建一个使用默认属性初始化对象的打字稿类/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: ''
}

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

标签: javascripttypescript

解决方案


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

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

推荐阅读