Skip to content

Object is possibly 'null' due to slight difference in code with strictNullChecks #27431

Closed
@castaneai

Description

@castaneai

Typescript Version: 3.1.1

I found a strange behavior about strictNullChecks. Why?

It works

let a: string | null = null;
(() => a = 'str')();
console.log(a.length);

http://www.typescriptlang.org/play/#src=let%20a%3A%20string%20%7C%20null%20%3D%20null%3B%0D%0A(()%20%3D%3E%20a%20%3D%20'str')()%3B%0D%0Aconsole.log(a.length)%3B

Not working

let a: string | null = null;
const f = (() => a = 'str');
f();
console.log(a.length);

http://www.typescriptlang.org/play/#src=let%20a%3A%20string%20%7C%20null%20%3D%20null%3B%0D%0Aconst%20f%20%3D%20(()%20%3D%3E%20a%20%3D%20'str')%3B%0D%0Af()%3B%0D%0Aconsole.log(a.length)%3B

$ tsc --strictNullChecks ng.ts
ng.ts:4:13 - error TS2531: Object is possibly 'null'.

4 console.log(a.length);
              ~

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