microsoft / microsoft/TypeScript

Warn/error when testing a non-nullable type for null

Open
#10,477 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

TypeScript Version: 2.0.0

TL;DR:

If a project is configured for strict null checks, checking a variable which is typed as non-null is nonsense and could indicate a type mismatch.

Code:

Here's a motivating example I experienced:

async function someFunc1(): Promise<string | null> {
  // do some stuff and return the appropriately typed promise
}

async function someFunc2(): Promise<boolean> {
  // Negating a non-null Promise is crazy talk, but here I go!
  return !!someFunc1()
}

Of course what I really meant was:

async function someFunc2(): Promise<boolean> {
  return !!(await someFunc1())
}

Expected behavior:

TypeScript warns that I'm effectively testing my non-null Promise for null, and points out that that's nonsense.

Actual behavior:

TypeScript happily accepted the code, which led to a bug.

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, test, or entry point is named in the issue. Start by reviewing the strict-null-checking behavior described in the examples and trace how TypeScript handles null tests on non-nullable expressions; done means the incorrect check produces a diagnostic without rejecting valid nullable checks.

Written by the indexing model from the issue text.

Assessment

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