Skip to content

Object unexpectedly undefined #52104

@mqualizz

Description

@mqualizz

Bug Report

🔎 Search Terms

undefined object, callback, closure, hoisting, arrow function

🕗 Version & Regression Information

  • This is the behavior in every version I tried (every version available in the playground, from 3.3.3 to Nightly 5.0.0), and I reviewed the FAQ for entries about undefined, closure, hoisting

⏯ Playground Link

Playground link with relevant code

💻 Code

const fooMap:Map<string,Array<number>> = new Map()

function someFunction(arg:Array<number>) {
    //...
}

const values = [1, 2, 3, 4, 5];

let foo = fooMap.get("a");

if (foo == null) {
    foo = [];
}

// The issue is this line, where TS says that `foo` may be undefined
values.forEach((v) => foo.push(v));

// In this line, TS recognizes that `foo` is not undefined
someFunction(foo);

🙁 Actual behavior

A variable (in this case, foo) is being marked as possibly undefined when used inside of a closure, although it will never be null at that point.

🙂 Expected behavior

I expect foo to be not-null.

I apologize if the observed behaviour is expected -- but, if it is, can someone explain why?

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions