【问题标题】:Objects type casting in TypeScriptTypeScript 中的对象类型转换
【发布时间】:2026-02-24 12:10:02
【问题描述】:

使用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 的类型为TFirstTSecond,即使该函数接收到TMyObject。我可以毫无问题地使用myObject.foo,因为这两种类型都有。

另一方面,我在 otherFunction 中使用了 util 函数 isFirstOrSecondUtil(与在 someFunction 中所做的检查相同),显然在这种情况下类型检查失败。在第 38 行,TypeScript 不知道确切的类型是 myObject。我希望能够控制台 myObject.foo,但 TypeScript 因 Property 'foo' does not exist on type 'TThird'. 而失败

有什么建议可以通过 util 函数进行正确的类型转换吗?

【问题讨论】:

    标签: javascript typescript enums casting


    【解决方案1】:

    你可以告诉 Typescript 返回的布尔值表示类型:

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

    docs

    【讨论】:

    • 哇!太棒了。感谢您的快速回答。
    最近更新 更多