Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
castaneai opened this issue Sep 28, 2018 · 3 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@castaneai
Copy link

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);
              ~
@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Sep 28, 2018
@RyanCavanaugh
Copy link
Member

Function references aren't expanded for control flow analysis purposes, but IIFEs are

@sirdiego
Copy link

sirdiego commented Nov 2, 2020

Function references aren't expanded for control flow analysis purposes, but IIFEs are

I've got a slightly more "complex" setup and I don't get why there is an error in line 12 but not in 11. Is this the reason?

Code (TS Playground):

interface Test {
    test: Test | null
    id: String
}

const testInstance: Test = {} as Test
const myArray: Array<Test> = []

if (
    null !== testInstance.test && 
    testInstance.test.id &&                                                   // Line 11
    myArray.findIndex(p => p.id === testInstance.test.id)   // Line 12
) {
    console.log('Test')
}

Is it worth opening a new issue?

@RyanCavanaugh
Copy link
Member

See #11498

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

3 participants