Search code examples
typescripttypeguards

Is it possible to make a complex typeguard function that infers return type based on provided argument?


Let's say I have two unions:

type Animal = "cat" | "elephant"
type Vehicle = "some small vehicle" | "truck"

And I want to make a single function that infers which union it's working with and then guards the type within the specific union - something like:

function isBig(thing: Animal | Vehicle): (typeof thing extends Animal) ? thing is "elephant" : thing is "truck" {
    if(isAnimal(thing)) return thing === "elephant"
    return thing === "truck"
}

Is this doable? Or even reasonable?


Solution

  • You can do it with two function signatures:

    type Animal = "cat" | "elephant"
    type Vehicle = "some small vehicle" | "truck"
    
    function isBig(thing: Animal): thing is "elephant"
    function isBig(thing: Vehicle): thing is "truck"
    function isBig(thing: Animal | Vehicle) {
        if(isAnimal(thing)) return thing === "elephant"
        return thing === "truck"
    }