microsoft / microsoft/TypeScript

TS doesn't narrow generic parameter T to null, despite an explicit comparison

Open
#57,803 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

🔎 Search Terms

T to null

🕗 Version & Regression Information
  • This is a type narrowing issue
  • This is the behavior in every version I tried
⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.5.0-pr-57465-110#code/GYVwdgxgLglg9mABDAzgORAG0wHgCoB8AFAG4CGmIApgFyJ4CUiA3gFAD07i3P3AegH5W3GMESkK1RAF5ZiMFkxM2vcpSrdO9ADSIUACzhYAJogBGGhdmGIAvqxsAnKlBCOkaqbOnzFAblZ7IA

💻 Code
function isNull<T>(value: T) {
  if (value === null) {
    value  // T, should be null
  }

  return value === null;
}

🙁 Actual behavior

value is T inside the if block of value === null (explicit comparison)

🙂 Expected behavior

value should be of type null inside the if block of value === null

Additional information about the issue

No response

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 reproduction and trace the compiler's type-narrowing behavior for the explicit value === null check on generic T. Confirm the result against the expected type shown in the example; done means value is treated as null inside the if block without regressing the return comparison.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.