microsoft / microsoft/TypeScript

Non-null assertions infringe a responsibility of optional chaining

Open
#35,025 15 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Proposal Suggestion
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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.