microsoft / microsoft/TypeScript

Type guard/Equality narrowing doesn't work on "any"

Open
#54,239 2 comments 0 reactions 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

Bug Report

🔎 Search Terms

type guard equality narrowing strict equal equality

🕗 Version & Regression Information
⏯ Playground Link

https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAgEYEMBOAKZWDmAXHhAJ7ICUyA3sMvcnCMrgcgLyfIRgA2vlGnQYjMAUxhhMKAgG5h9AL7AFjZq0z4OXEOl4BnMYNojREqTM3yRy5SqA

💻 Code
function bar( arg: any ) {
    if ( arg === null ) {
        return arg;
    }

    if ( arg === false ) {
        return arg;
    }
}
🙁 Actual behavior

arg should be null/false inside the if conditions

🙂 Expected behavior

arg is any

The docs say this should work https://www.typescriptlang.org/docs/handbook/2/narrowing.html
When using unknown instead of any it works perfectly fine. I think adjusting this, so it works for any too, isn't too far fetched.

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 narrowing behavior in the linked TypeScript Playground and compare it with the documented behavior for unknown. Trace the type-checker path for equality narrowing of any, then add regression coverage showing null and false are narrowed as expected and run the relevant compiler tests.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.