Skip to content

Type guard fails to narrow union type #1802

Closed
@altano

Description

@altano

This works, AS EXPECTED:

class Cat {}
class Dog {}

function logType1(animal: Cat|Dog) {
    if (animal instanceof Cat) {
        console.log("cat");
    }
    else if (animal instanceof Dog) {
        console.log("dog");
    }
}

This doesn't work, which is debatable since undefined instanceof Cat is legal JS but I prefer the type warning since it catches errors:

function logType2(animal: Cat|Dog|void) {
    if (animal instanceof Cat) {
        console.log("cat");
    }
    else if (animal instanceof Dog) {
        console.log("dog");
    }
}

This doesn't work, but I would definitely expect it to:

function logType3(animal: Cat|Dog|void) {
    if (typeof animal === "undefined" || animal === null) { // edited to check for null as well, since void can be either
        console.log("no animal");
    }
    else if (animal instanceof Cat) {
        console.log("cat");
    }
    else if (animal instanceof Dog) {
        console.log("dog");
    }
}

See playground for code.

As it stands, if a union type contains void, I don't know how to use instanceof with it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDuplicateAn existing issue was already createdFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions