Michal Kurz
Michal Kurz

Reputation: 2095

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?

Upvotes: 0

Views: 22

Answers (1)

blaumeise20
blaumeise20

Reputation: 2220

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"
}

Upvotes: 1

Related Questions