繁体   English   中英

TypeScript中的对象类型转换

[英]Objects type casting in TypeScript

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完全知道myObject的类型为TFirstTSecond即使该函数接收到TMyObject 我可以使用myObject.foo而不会出现任何问题,因为两种类型的此属性都有。

在另一方面,我使用UTIL功能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;

文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM