设置布尔型打字稿的默认值

时间:2018-11-19 11:22:29

标签: angular typescript boolean

我有一个对象:

export class ReccurrenceModel {
    fromDate: Date;
    toDate: Date;
    weeklyReccurrence: number;
    state: State;
    isMonday: boolean;
    isTuesday: boolean;
    isWednesday: boolean;
    isThursday: boolean;
    isFriday: boolean;
    fromDateToReturn: Date;
    toDateToReturn: Date;
}

我这样使用它

  if (this.reccurrenceSelected === true) {
      this.reccurrence.isMonday = this.mondaySelected;
      this.reccurrence.isTuesday = this.tuesdaySelected;
      this.reccurrence.isWednesday = this.wednesdaySelected;
      this.reccurrence.isThursday = this.thursdaySelected;
      this.reccurrence.isFriday = this.fridaySelected;
}

我想为它们设置一个默认值-false,因为如果不在UI中设置它们,它们将是未定义的,并且我不希望这样做。

如何在打字稿中设置布尔值的默认值?

5 个答案:

答案 0 :(得分:4)

undefinedfalse都是伪造的值,您可以用相同的方法进行测试。

但是默认值是用

设置的
export class ReccurrenceModel {
    fromDate: Date;
    toDate: Date;
    weeklyReccurrence: number;
    state: State;
    isMonday = false;
    isTuesday = false;
    ...
    fromDateToReturn: Date;
    toDateToReturn: Date;
}

答案 1 :(得分:2)

在您可以使用的UI级别上没有做任何大的改变。两者都是用户界面的虚假值。

您可以设置任何人。

variableName = false 

variableName: boolean;

variableName,您可以使用任一UI在默认情况下都将其视为false,直到将其值分配为true为止。

答案 2 :(得分:1)

我建议在课堂上使用getterssetters

export class ReccurrenceModel {
    fromDate: Date;
    toDate: Date;
    weeklyReccurrence: number;
    state: State;
    isMonday: boolean;
    isTuesday: boolean;
    isWednesday: boolean;
    isThursday: boolean;
    isFriday: boolean;
    fromDateToReturn: Date;
    toDateToReturn: Date;
        ...

        get fromDate() {
            return this.fromDate|| "";
        }
        get isMonday() {
            return this.isMonday|| false;
        }
    }

答案 3 :(得分:1)

我将添加一个默认的构造函数并执行以下操作:

export class ReccurrenceModel {
    fromDate: Date;
    toDate: Date;
    weeklyReccurrence: number;
    state: State;
    isMonday: boolean;
    isTuesday: boolean;
    isWednesday: boolean;
    isThursday: boolean;
    isFriday: boolean;
    fromDateToReturn: Date;
    toDateToReturn: Date;

    constructor(){
      this.isMonday = false;
      this.isTuesday = false;
      this.isWednesday = false;
      this.isThursday = false;
      this.isFriday = false;
    }
}

后来我会做这样的事情:

this.reccurrence = new ReccurrenceModel();

以上行将初始化必填字段。 您可以在调用console.log(this.reccurrence)

之后执行constructor来确认这一点

答案 4 :(得分:1)

您可以放

      this.isMonday = false;
      this.isTuesday = false;
      this.isWednesday = false;
      this.isThursday = false;
      this.isFriday = false;

这些也在ngOnInit()方法中,这是首先被调用的方法。 找到ngOnInit()和构造函数之间的区别,请访问Difference between Constructor and ngOnInit