microsoft / microsoft/TypeScript

Object is possibly undefined after undefined check on readonly property

Open
#39,340 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Experience Enhancement Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.7.4, 3.9.2

Search Terms:
Object is possibly undefined
undefined readonly callback
Code

class Test {
  private readonly testProperty?: { value: number };
  public constructor(testProperty: { value: number }) {
    this.testProperty = testProperty;
  }

  public method() {
    if (this.testProperty) {
      Promise.resolve().then(() => this.testProperty.value); //Object is possibly undefined
    }
  }
}

Expected behavior:
testProperty should not be resolved as possibly undefined as this is not possible in this scenario as the property has already been checked and it is marked as readonly.

Actual behavior:
testProperty is possibly undefined, requiring another undefined check.

Playground Link:
https://www.typescriptlang.org/play/#code/MYGwhgzhAEAqCmEAu0DeAoa0AOAnAlgG5hLzS7xgAmA9gHYgCe0pyACrjdvLkowPwAuNNGIgArvGF1xAWwBGPaAF8A3Jhzj5IfMGjB6yXOOBIauABSskHLjz7DUosBKnQZCpcoCUaDViQAC3wIADprW25eZgBeFkQbTii+dSxldA1sLR09WXggmioLXwwsLHwAM2grYLCIpPtGEv8y21kQ+FCKCBoQQnhi8MD4Ogti6BiAPhZa8ITIxtCxSW9VaAB6dYB5eQAreFNoEJwaKHxtZnE6KngK-Dp4Khb0tPRlIA

Related Issues:

Similar issues but these i understand why TypeScript would report an error, in my case the property is readonly so it seems like a bug to me.
https://github.com/microsoft/TypeScript/issues/38053
https://github.com/microsoft/TypeScript/issues/11498

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Playground reproduction and compare the behavior described in related issues #38053 and #11498. Trace type-checking for the readonly optional property inside the Promise callback; done means the supplied example no longer reports “possibly undefined” or the expected behavior is otherwise resolved.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.