microsoft / microsoft/TypeScript

Object is possibly null inside a closure defined within a const constraint

Open
#36,193 15 comments 0 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

Search: Object is possibly null, narrowed type, type constraint, closure

Code

const foo: string | null = 'bar'
if (foo) {
    function baz() {
        console.log(foo.length)  // Object is possibly 'null'
    }
}

Expected behavior:

Compiles

Actual behavior:

const foo: string | null
Object is possibly 'null'

Playground Link:

Playground

Related Issues:

#12113, #33319, #9998

Discussion:

By design, type narrowings are reset inside closures. This makes sense, but there is one case where better assumptions can be made: when the closure is defined inside a type constraint block AND the type narrowing is based on a const value. Even if called from async, the closure is still referencing a const and was created after a suitable type constraint occurred.

Thoughts?

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 by reproducing the provided TypeScript example in the linked Playground and compare it with related issues #12113, #33319, and #9998. The issue names no source file or test; done would mean reaching agreement on whether this const-based narrowing should remain valid inside the closure and demonstrating the agreed behavior with a compiling example.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.