Skip to content

Strict mode: Object is possibly 'null' when it really isn't #16285

Closed
@zaggino

Description

@zaggino

TypeScript Version: 2.3.4

Code

/*
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "strict": true
  }
}
*/

let maybeNumber = Math.random() > 0.5 ? 2 : null;
let ones = [1, 1, 1];
let twoes;
if (maybeNumber) {
  twoes = ones.map(x => x * maybeNumber);
}
console.log(maybeNumber, twoes);

Expected behavior:
Compilation passes, TS should know that .map function will be executed immediately and so maybeNumber will not be null

Actual behavior:
Compilation error: error TS2531: Object is possibly 'null'

Weird:
When I change let maybeNumber to const maybeNumber compilation passes for some reason, even though type of maybeNumber should be still number | null

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions