Skip to content

Typescript throws TS2532 although accessed value is asserted to be set with if statementΒ #53702

@McTom234

Description

@McTom234

Bug Report

πŸ”Ž Search Terms

  • language server undefined
  • TS2532

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Common "Bugs" That Aren't Bugs

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

enum En {
  A = 'a',
  B = 'b',
}

class Test {
  a?: Stub = undefined;
  b?: Stub = undefined

  public fails(stub: Stub, en: En): boolean {
    if (this[en]) return stub.id === this[en].id;
    return false;
  }

  public works(stub: Stub, en: En) {
    const thisStub = this[en];
    if (thisStub) return stub.id === thisStub.id;
    return false;
  }
}

class Stub {
  id: number = 0
}

πŸ™ Actual behavior

TypeScript gives the error TS2532: Object is possibly 'undefined'. in the method fails.

πŸ™‚ Expected behavior

The if statement asserts, that this property is set and no modification has been made to the code since the statement. The variable should be set and as the method works it works as expected by setting an extra variable for the accessed property.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions