设置布尔打字稿的默认值

use*_*496 9 boolean typescript angular

我有一个对象:

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;
}
Run Code Online (Sandbox Code Playgroud)

我像这样使用它

  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;
}
Run Code Online (Sandbox Code Playgroud)

我想为它们设置一个默认值 - false 因为如果我不在 UI 中设置它们,它们将是未定义的,我不想要那样。

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

Par*_*ain 10

也不会对您可以使用的 UI 级别进行任何重大更改。两者都是 UI 的假值。

你可以设置任何人。

variableName = false 
Run Code Online (Sandbox Code Playgroud)

或者

variableName: boolean;
Run Code Online (Sandbox Code Playgroud)

variableName 您可以使用任一 UI 默认将其视为 false,直到您将其值指定为 true。

  • 听起来很棒,你现在知道一些新的东西,但是伙计,这不是对我的单一赞成,而是关于正确或不正确的。无论如何感谢您删除downvote :) (2认同)

Cru*_*ine 6

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

后来我会做这样的事情:,

this.reccurrence = new ReccurrenceModel();
Run Code Online (Sandbox Code Playgroud)

上面的行将初始化所需的字段。您可以通过console.log(this.reccurrence)在调用 constructor


小智 5

undefined,以及false,都是可以用相同方式测试的假值。

但默认值设置为

export class ReccurrenceModel {
    fromDate: Date;
    toDate: Date;
    weeklyReccurrence: number;
    state: State;
    isMonday = false;
    isTuesday = false;
    ...
    fromDateToReturn: Date;
    toDateToReturn: Date;
}
Run Code Online (Sandbox Code Playgroud)