假设我有两个联合:
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"
}