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

Type narrowed to never, incorrectly #27103

Closed
ljharb opened this issue Sep 14, 2018 · 3 comments
Closed

Type narrowed to never, incorrectly #27103

ljharb opened this issue Sep 14, 2018 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@ljharb
Copy link
Contributor

ljharb commented Sep 14, 2018

TypeScript Version: latest

Search Terms: n/a

Code

function f(a?: {}) {
    if (!a) {
        // filters out falsy values:
        //  - `null`
        //  - `undefined`
        //  - `false`
        //  - `NaN`
        //  - `0` / `-0`
        //  - `''`
        return {};
    }

    // here, the type of `a` has been narrowed from "optional {}"
    // to just "{} minus `object`" (object-coercible, ie, anything but null/undefined, but not `object`)
    // effectively, this is `string | number | symbol | boolean | Function`

    if (typeof a !== 'object') {
        // `a` here could be the following values:
        //   - a function
        //   - `true``
        //   - a non-zero non-`NaN`` number
        //   - a non-empty string
        //   - a symbol
        return a; // however, the type inferred here is `never`
    }

    // here, `a` has a verifiably certain type of `object`.
    // because of the type guard above.
    return a; // however, the type is reported as `{}` 
}

Expected behavior: The type of a inside the if block will be either {}, or better, string | number | symbol | boolean | Function.

Actual behavior: The type of a inside the if block is never, which is flat out incorrect.

Playground Link: link

Related Issues: not sure how to search for it

@DanielRosenwasser
Copy link
Member

It's kind of funny, but we were actually talking about #18196 right as you were opening this issue.

But filing this as a duplicate of #18196

@DanielRosenwasser DanielRosenwasser added the Duplicate An existing issue was already created label Sep 14, 2018
@ljharb
Copy link
Contributor Author

ljharb commented Sep 18, 2018

This may be addressed by #27157; it can be closed or left open til the next release, as you like.

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for 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

3 participants