打字稿:使用类中的默认值初始化对象

时间:2020-03-24 04:38:44

标签: javascript typescript

如何创建一个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: ''
}

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

3 个答案:

答案 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)

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

如果我用打字稿写这个

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显示了预期的对象结构