Skip to content
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

Incorrect type inferred with early return #19698

Closed
Bibliofile opened this issue Nov 2, 2017 · 1 comment · Fixed by #56908
Closed

Incorrect type inferred with early return #19698

Bibliofile opened this issue Nov 2, 2017 · 1 comment · Fixed by #56908
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@Bibliofile
Copy link

When returning early from a function, types are not inferred correctly in functions defined later in the function. This occurs only with strictNullChecks turned on. Playground.

TypeScript Version: [email protected], [email protected]

Code

interface hasMethods {
    remove(): void
    getExports(key: string): {[key: string]: any} | undefined
}

let obj: hasMethods = {
    remove: () => { },
    getExports: () => undefined
}

;(function () {
    let x = obj.getExports('test')
    if (!x) return
    // No error, as expected
    x.test()
    // Error, x might be undefined
    obj.remove = () => x.test()
}())
@ghost
Copy link

ghost commented Nov 2, 2017

x is a mutable variable. Since x might be mutated at some point, we can't be sure that a reference to x in a callback will still have x defined. (#9998)
In this case you're not actually mutating x, so use const instead. There's a lint rule for that too.

@ghost ghost added the Working as Intended The behavior described is the intended behavior; this is not a bug label Nov 2, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant