microsoft / microsoft/TypeScript

Nullish coalescing should always include the type of the right operand

Open
#36,393 8 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

$ ./node_modules/.bin/tsc --version
Version 3.7.2

Search Terms:

Code

A toy example would be something like this.

let foo: string = "";
foo = "bar" ?? 123;

This one is obviously fine since "bar" is always truthy.

However, this becomes a little bit problematic when you consider the idiom of having Record objects and checking their truthiness before using them.

const elts = ["foo", "bar", "spam", "spam", "foo", "eggs"];
const counts: Record<string, number>;
for (const elt of elts) {
  // This really **should** raise an error.
  counts[elt] = counts[elt] ?? "zero";
  counts[elt] += 1;
}

Expected behavior:
An error should be raised.

Actual behavior:
Curiously, an error is not raised in strict mode but is raised in un-strict mode.

$ ./node_modules/.bin/tsc ./foo.ts 
foo.ts:5:3 - error TS2322: Type 'number | "zero"' is not assignable to type 'number'.
  Type '"zero"' is not assignable to type 'number'.

5   counts[elt] = counts[elt] ?? "zero";
    ~~~~~~~~~~~


Found 1 error.
$ ./node_modules/.bin/tsc --strict ./foo.ts
# No error, exits 0 and emits JS.

Playground Link:
Playground Link

Toggling the strictNullChecks config option will show the issue.

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

Reproduce the examples with TypeScript 3.7.2 using both the default compiler command and --strict, then compare the diagnostics for the nullish-coalescing assignment. The work is done when the reported expression consistently includes the right operand's type and raises the expected error under the stated configuration.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.