Reputation: 2095
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
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