microsoft / microsoft/TypeScript

Type narrowing is lost when using logical OR assignment

Open
#44,553 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

logical assignment, narrowing

🕗 Version & Regression Information

The behaviour is consistent across all versions since the introduction of logical assignment operators in TypeScript 4.0.
Checked range from 4.0.5 to Nightly, no changes in behaviour observed.

⏯ Playground Link

Playground link with relevant code

💻 Code
type F = () => number;

type R = {
  [ x: string ]: R | F | undefined
}

const isFunc = <T extends (...args: any[]) => any>(maybe:unknown) : maybe is T => typeof maybe === "function";

const check = (i: R) => {

  let tmp:R = i;

  let curr = tmp["something"]; // R | F | undefined, expected

  if( isFunc<F>(curr) ) return;

  curr // R | undefined, expected

  tmp = curr || (curr = {}); //ok, expected

  tmp = curr ||= {}; // Type 'R | F' is not assignable to type 'R'.
};
🙁 Actual behavior

Error 2322 on the second tmp assignment because R | F is not narrowed to R as with the curr || (curr = {})

🙂 Expected behavior

No error since both assignments to tmp are functionally equivalent
(I might be missing something obvious about how logical assignment is intended to work from the type system standpoint)

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 with the linked TypeScript Playground and reproduce the difference between curr || (curr = {}) and curr ||= {} across the stated versions. Trace the control-flow narrowing behavior for logical assignment; done means the equivalent code type-checks without the reported TS2322 error.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.