Skip to content

strictNullChecks + non-null flow control + higher-order function = spurious "Object is possibly 'undefined'" #29392

Closed
@brandonbloom

Description

@brandonbloom

I'm basically reopenning
#10642 since the justification provided for the expected behavior doesn't apply in my case.

Here's a playground, be sure to turn on strictNullChecks:

https://www.typescriptlang.org/play/index.html#src=const%20map%20=%20new%20Map%3Cstring,%20%7Battr:%20number%7D%3E();%0Alet%20obj%20=%20map.get('key');%0Aif%20(!obj)%20%7B%0A%20%20obj%20=%20%7B%20attr:%201%20%7D;%0A%7D%0A[].map(elem%20=%3E%20%7B%0A%20%20console.log(obj.attr);%0A%7D)

TypeScript Version: 3.3.0-dev.201xxxxx

Search Terms:

  • strictNullChecks
  • control-flow
  • undefined
  • higher-order function (map, filter, forEach)
  • "Object is possibly 'undefined'"

Code

const map = new Map<string, {attr: number}>();
let obj = map.get('key');
if (!obj) {
  obj = { attr: 1 };
}
[].map(elem => {
  console.log(obj.attr); // error occurs on this line
})

Expected behavior:

TypeScript should detect that there's no way obj can become undefined during the evaluation of the map call.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions