Skip to content

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

Open
@benallfree

Description

@benallfree

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions