microsoft / microsoft/TypeScript
Non-null assertions infringe a responsibility of optional chaining
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Because @RyanCavanaugh couldn't understand what is the problem, I reexplain it.
In the following case, a responsibility of optional chaining is making a return type Element | undefined.
// a is string | null | undefined
const a = document.querySelector('_')?.textContent;
In the following case, non-null assertion has broken the safeness made by optional chaining.
// a is string
const a = document.querySelector('_')?.textContent!;
It is obvious that optional chaining was not considered when non-null assertion operator was designed. TypeScript has to consider what is the best design and what to do via reconsidering the design of non-null assertion operator.
TypeScript Version: 3.7.x-dev.20191105
Search Terms:
Code
const a = document.querySelector('_')?.textContent!;
Expected behavior:
a is string | undefined.
Actual behavior:
a is string.
Playground Link:
Related Issues:
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No file or test is named. Start by reproducing the reported TypeScript type-checking example with optional chaining followed by a non-null assertion, then trace how these operators determine the inferred type. Done means the behavior is resolved according to the expected type and covered by a regression test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100