Skip to content

Non-null assertions infringe a responsibility of optional chaining #35025

Open
@falsandtru

Description

@falsandtru

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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions