Typescript 是否可以创建一个复杂的typeguard函数,根据提供的参数推断返回类型?

Typescript 是否可以创建一个复杂的typeguard函数,根据提供的参数推断返回类型?,typescript,typeguards,Typescript,Typeguards,假设我有两个工会: type Animal = "cat" | "elephant" type Vehicle = "some small vehicle" | "truck" 我想用一个函数来推断它使用的是哪个联合,然后保护特定联合中的类型,比如: function isBig(thing: Animal | Vehicle): (typeof thing extends Animal) ? thing is &

假设我有两个工会:

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