Skip to content

Unexpected type narrowing for variable (outer scope) assignment in function #36403

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
cschuller opened this issue Jan 24, 2020 · 2 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@cschuller
Copy link

TypeScript Version: 3.8.0-dev20200122

Search Terms:
property does not exist on type never

Code

class Person {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}
 
let foo: Person | null = null;

function initialize() {
    foo = new Person('foo');
}

initialize();

if (foo) {
    console.log(foo.name); // Property 'name' does not exist on type 'never'.
}

Expected behavior:
No compile error.

Actual behavior:
Code throws a Property 'name' does not exist on type 'never'.

Playground Link:
playground example

Related Issues:
#35644
Labelled as fix available for 3.8.1, but does not work for 3.8.0-dev20200122

@jcalz
Copy link
Contributor

jcalz commented Jan 24, 2020

duplicate of #9998; the compiler has no idea that initialize() has an implication for the type of foo.

@cschuller
Copy link
Author

@jcalz Thanks - Quite a long discussion, good arguments on both sides. I am more in favor of turning the optimistic prediction off (or make it configurable or warning level), but at least we could re-phrase the error message.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 24, 2020
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

3 participants