typescript - 解决不兼容的类型而不在 TypeScript 中进行转换?

我有一个泛型类型 (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);
}

相似文章

随机推荐

最新文章