microsoft / microsoft/TypeScript

Suggestion: should non-null assert propagate?

Open
#9,640 16 comments 5 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

I was wondering whether ! should be taken into account by the dataflow analysis, and I don't see why it shouldn't.

It is like a cast that says "this value is not null", so from this point I guess the compiler could remove undefined/null from future uses.

For example, I use ! to work around #9631, so I have code that looks like (simplified):

protected dataArrayChanged(changes: ChangeRecord[]) {
  // #9631: TS incorrectly infers `change: ChangeRecord | undefined`
  for (const change of changes) {
    for (let i = 0; i < change!.removed.length; i++)
      this.dt.row(i).remove();
    if (change!.addedCount > 0)
      this.dt.rows.add(this.data.slice(change!.index, change!.index + change!.addedCount));
  }
  this.dt.draw();
}

Observe how I added 5 ! to make change not null.
The first one could have been enough. After all, once I say "change is not undefined", there is no reason to assume it could be until I modify the variable again.

// Let's say I know x is not undefined
const x: number | undefined;
// Here x: number | undefined, so x! is required
x!.toString();
// Here x: number because of x! above
x.toString(); // ok

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 by reviewing the dataflow-analysis behavior described in this issue and the related context in #9631. Reproduce the examples involving repeated non-null assertions and determine the intended propagation semantics. Done means the behavior is resolved consistently and covered by appropriate compiler tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
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.