Skip to content

Refinement of object works and it doesn't #32301

Closed

Description

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()?

Activity

  1. lll000111 commented on Jul 8, 2019

    @lll000111
    Author

    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;
    }
  2. jack-williams commented on Jul 8, 2019

    @jack-williams
    Collaborator

    Duplicate of #28131

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions