Skip to content

Refinement of object works and it doesn't #32301

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
lll000111 opened this issue Jul 8, 2019 · 2 comments
Closed

Refinement of object works and it doesn't #32301

lll000111 opened this issue Jul 8, 2019 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@lll000111
Copy link

lll000111 commented Jul 8, 2019

I created a few tiny examples, one per demo function:

Playground link

In particular, these two:

function demoV1(thing: unknown): void {
    if (thing === null || typeof thing !== 'object') {
        throw new Error('not an object');
    }

    // ERROR: thing is object || null
    const obj: object = thing;
}

function demoV2(thing: unknown): void {
    if (typeof thing !== 'object') {
        throw new Error('not an object');
    }

    if (thing === null) {
        throw new Error('not an object');
    }

    // WORKS
    const obj: object = thing;
}

So... TypeScript does not understand an or operator "||" to test twp things in the same if()?

@lll000111
Copy link
Author

lll000111 commented Jul 8, 2019

Okay... so I found that the order of the individual tests matters, which is just as strange so I see no reason to close the issue.

Playground link

function demoV1(thing: unknown): void {
    if (typeof thing !== 'object' || thing === null) {
        throw new Error('not an object');
    }

    // WORKS
    const obj: object = thing;
}

function demoV2(thing: unknown): void {
    if (thing === null) {
        throw new Error('not an object');
    }

    if (typeof thing !== 'object') {
        throw new Error('not an object');
    }

     // ERROR: thing is object || null
    const obj: object = thing;
}

@jack-williams
Copy link
Collaborator

Duplicate of #28131

@sandersn sandersn added the Duplicate An existing issue was already created label Jul 8, 2019
@sandersn sandersn closed this as completed Jul 8, 2019
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