我有一个泛型类型 (GenericType),它有一个属性 (prop),它可以包含两个 values ("thing1" | "thing2") 之一。
我还有一个类型(Thing1Type),其中“prop”总是“thing1”。我想检查是否 prop = "thing1" 然后调用一个需要该类型签名的方法。我可以将“GenericType”转换为“Thing1Type”,但我想知道是否有更好的方法可以在不进行转换的情况下实现这一目标?
示例代码:
type GenericType = {
prop: "thing1" | "thing2"
};
type Thing1Type = {
prop: "thing1";
};
const myObj: GenericType = { prop: "thing1" };
const myMethod = (obj: Thing1Type) => {
console.log(obj);
}
if (myObj.prop == "thing1") {
myMethod(myObj);
}
回答1
基本上,您需要这样的类型保护:
function hasThing1(obj: GenericType): obj is {prop:"thing1"}
{
return obj?.prop === "thing1"
}
然后你可以安全地调用你的函数:
if(hasThing1(myObj)){
myMethod(myObj)
}