Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
McTom234 opened this issue Apr 9, 2023 · 2 comments

Comments

@McTom234
Copy link

McTom234 commented Apr 9, 2023

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.

@MartinJohns
Copy link
Contributor

Duplicate of #10530 and oh so many others. Type narrowing does not occur for indexed access forms e[k] where k is not a literal.

@McTom234
Copy link
Author

McTom234 commented Apr 9, 2023

Oh, sorry! I had no idea which keywords would work to find the right duplicates. Do you know, if this will be fixed at any point?

@McTom234 McTom234 closed this as completed Apr 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants