使用 enum
进行类型转换在 TypeScript 中效果非常好,直到您想通过 util 函数来完成它。这是一个例子:
enum MyTypes {
FIRST = "FIRST",
SECOND = "SECOND",
THIRD = "THIRD"
}
type TFirst = {
type: MyTypes.FIRST
foo: string
}
type TSecond = {
type: MyTypes.SECOND
foo: string
}
type TThird = {
type: MyTypes.THIRD
bar: string
}
type TMyObject = TFirst | TSecond | TThird
const someFunction = (myObject: TMyObject) => {
if (myObject.type === MyTypes.FIRST || myObject.type === MyTypes.SECOND) {
// here typescript knows exactly that myObject is TFirst or TSecond
console.log(myObject.foo)
}
}
const isFirstOrSecondUtil = (myObject: TMyObject): boolean => {
return myObject.type === MyTypes.FIRST || myObject.type === MyTypes.SECOND
}
const otherFunction = (myObject: TMyObject) => {
if (isFirstOrSecondUtil(myObject)) {
// typescript is aware that myObject is TMyObject, but does not know which type exactly
console.log(myObject.foo)
}
}
您可以在 TypeScript Playgroud 中测试它.
正如您在 someFunction
中的第 27 行所看到的,TypeScript 完全知道 myObject
的类型为 TFirst
或 TSecond
即使该函数接收 TMyObject
。我可以毫无问题地使用 myObject.foo
,因为这两种类型都具有此属性。
另一方面,我在 otherFunction
中使用 util 函数 isFirstOrSecondUtil
(它执行与 someFunction
中相同的检查),并且显然,在这种情况下类型检查失败。第 38 行 TypeScript 不知道 myObject
到底是哪种类型。我希望能够控制台 myObject.foo
,但 TypeScript 失败,并显示 Property 'foo' does not exit on type 'TThird'.
有什么建议如何通过 util 函数进行正确的类型转换吗?
最佳答案
你可以告诉 Typescript 返回的 bool 值表示类型:
const isFirstOrSecondUtil = (myObject: TMyObject): myObject is TFirst | TSecond =>
myObject.type === MyTypes.FIRST || myObject.type === MyTypes.SECOND;
关于javascript - TypeScript 中的对象类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57160283/