是否可以制作一个复杂的类型保护函数,根据提供的参数推断 return 类型?

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

假设我有两个工会:

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

我想制作一个函数来推断它正在使用哪个联合,然后在特定联合内保护类型 - 类似于:

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

这可行吗?甚至合理?

您可以使用两个函数签名来完成:

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