使用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中进行测试。
正如你在27行中看到的那样,someFunction TypeScript完全意识到myObjectTFirstTSecond的类型,即使该函数接收TMyObject。我可以使用myObject.foo而不会有任何问题,因为这两种类型的属性都有。
另一方面,我使用的是UTI函数isFirstOrSecondUtil(它在someFunction中做了与otherFunction中相同的检查),显然在这种情况下类型检查失败了。在第38行,typescript不知道哪种类型是myObject。我希望能够控制myObject.foo,但typescript失败的原因是Property 'foo' does not exist on type 'TThird'.
有什么建议可以通过util函数进行正确的类型转换吗?

最佳答案

您可以告诉typescript,返回的布尔值指示类型:

 const isFirstOrSecondUtil = (myObject: TMyObject): myObject is TFirst | TSecond =>
   myObject.type === MyTypes.FIRST || myObject.type === MyTypes.SECOND;

docs

09-25 17:15
查看更多