【发布时间】:2021-04-14 02:50:31
【问题描述】:
假设我有两个工会:
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"
}
这可行吗?甚至合理?
【问题讨论】:
标签: typescript typeguards