Skip to content

allow storing results of narrowing of class properties in booleans for further narrowing #53267

Closed
@SteveRusin

Description

@SteveRusin

Bug Report

🔎 Search Terms

https://www.google.com/search?q=typescript+does+not+narrow+type+of+stored+variable&oq=typescript+does+not+narrow+type+of+stored+variable&aqs=chrome..69i57j69i64.8615j0j7&sourceid=chrome&ie=UTF-8

🕗 Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

Playground link with relevant code

💻 Code

class Utils {
  static isDefined<T>(value: T): value is NonNullable<T> {
    return value != null;
  };
}

class A {
  public testNumber: number | undefined;

  constructor() {
    const isNumber = Utils.isDefined(this.testNumber);

    if (isNumber) {
      // Type 'number | undefined' is not assignable to type 'number'
      const x: number = this.testNumber;
    }
  }
}

function foo(x: number | undefined) {
  const isNum = Utils.isDefined(x);

  if(isNum) {
    // Works. No error here
    const y: number = x;
  }
}

🙁 Actual behavior

The narrowed type of class property is not inferred if narrowing result stored in variable

I expect the type to be correctly inferred as it's working for regular variables inside a function
This PR fixed this bug for functions

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions