Why boolean becomes true?

前端 未结 2 1583
清酒与你
清酒与你 2021-01-12 12:00

Take a look at following code:

export class Smth {
  private flag: boolean;

  public update() {
    this.flag = true;

    this.inner();

    if (this.flag          


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 12:48

    TypeScript is kinda smart, in that it has a static analysis on your method, and it sees that you never assign anything other than false, at lease in this closure or context - which brings the type definition to assume your variable's type is false and not boolean. It does not look for changes in inner called methods.

    Think of the definition as if it were declared globally like this:

    export type boolean = true | false
    

    while false is only false, without the true there.

    There are several solutions:

    1. Assign the type from the get-go in the class declaration, like so:

      class MyClass {
        private flag: boolean = true
        ...
      }
      
    2. Just don't test for direct equality, use the boolean on its own:

      if (!this.flag) // instead of this.flag === false
      

提交回复
热议问题