代码之家  ›  专栏  ›  技术社区  ›  Vincent Tang

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

  •  0
  • Vincent Tang  · 技术社区  · 6 年前

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

    e、 这是我的课

    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 回复  |  直到 6 年前
        1
  •  0
  •   Oscar Velandia    6 年前

    您可以使用可选选项 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;
      }
    }
    
        2
  •  0
  •   azer-p    6 年前

    您的可选参数代码正在运行。你只需要这样开始

    newClass: StateModel = new StateModel(1);
    
        3
  •  0
  •   Vincent Tang    6 年前

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

    推荐文章