Skip to content

Declaring a var with interface type causes typescript to assume value can be undefined #27971

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
yuyaryshev opened this issue Oct 18, 2018 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@yuyaryshev
Copy link

yuyaryshev commented Oct 18, 2018

TypeScript Version: 3.2.0-dev.201xxxxx
Done

Search Terms:
declare variable interface undefined

Code

interface ifc {
    a?:number[]
    b?:string
}

let x : ifc = {a:[1]};
//x.a = [1];        // no error if this line is uncommented
x.a.push(2);        // <<<<<<< TS2532: Object is possibly 'undefined'.
x.b = 'aaa';

Expected behavior:
No error with strictNullChecks

Actual behavior:
TS2532: Object is possibly 'undefined'.

Playground Link:
Enable strictNullChecks in options

http://www.typescriptlang.org/play/#src=interface%20ifc%20%7B%0D%0A%20%20%20%20a%3F%3Anumber%5B%5D%0D%0A%20%20%20%20b%3F%3Astring%0D%0A%7D%0D%0A%0D%0Alet%20x%20%3A%20ifc%20%3D%20%7Ba%3A%5B1%5D%7D%3B%0D%0A%2F%2Fx.a%20%3D%20%5B1%5D%3B%20%20%20%20%20%20%20%20%2F%2F%20no%20error%20if%20this%20line%20is%20uncommented%0D%0Ax.a.push(2)%3B%20%20%20%20%20%20%20%20%2F%2F%20%3C%3C%3C%3C%3C%3C%3C%20TS2532%3A%20Object%20is%20possibly%20'undefined'.%0D%0Ax.b%20%3D%20'aaa'%3B

@weswigham weswigham added Suggestion An idea for TypeScript Experience Enhancement Noncontroversial enhancements labels Oct 18, 2018
@weswigham
Copy link
Member

AFAIK this is because we don't include member initializers when considering control flow initializer narrowing.

@RyanCavanaugh
Copy link
Member

Duplicate #20219

@RyanCavanaugh RyanCavanaugh added Duplicate An existing issue was already created and removed Experience Enhancement Noncontroversial enhancements Suggestion An idea for TypeScript labels Oct 18, 2018
@typescript-bot
Copy link
Collaborator

This issue has been marked as a duplicate and has seen no activity in the last day. It has been closed for automatic house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants