简体   繁体   English

TypeScript中的对象类型转换

[英]Objects type casting in TypeScript

Type casting with enum works really well in TypeScript until you want to do it via util function. enum类型转换在TypeScript中非常有效,直到您想通过util函数进行转换。 Here is an example: 这是一个例子:

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)
    }
}

You can test it in TypeScript Playgroud . 您可以在TypeScript Playgroud中对其进行测试。

As you can see on line 27 inside someFunction TypeScript is fully aware that myObject is of type TFirst or TSecond even though that function receives TMyObject . 正如您在第27行上看到的someFunction TypeScript完全知道myObject的类型为TFirstTSecond即使该函数接收到TMyObject I am able to use myObject.foo without any problems since this property both of types have. 我可以使用myObject.foo而不会出现任何问题,因为两种类型的此属性都有。

On the other hand I am using util function isFirstOrSecondUtil (which does the same checking as it is done in someFunction ) inside otherFunction and apparently type checking fails in this case. 在另一方面,我使用UTIL功能isFirstOrSecondUtil (它,因为它是在做同样的检查someFunction )内otherFunction ,显然类型检查在这种情况下失败。 On line 38 TypeScript does not know which type exactly is myObject . 在第38行,TypeScript不知道myObject到底是哪种类型。 I would expect to be able to console myObject.foo , but TypeScript fails with Property 'foo' does not exist on type 'TThird'. 我希望能够控制台myObject.foo ,但是TypeScript失败, Property 'foo' does not exist on type 'TThird'.

Any suggestion how to do proper type casting via util function? 任何建议如何通过util函数进行正确的类型转换?

You can tell Typescript that the boolean returned indicates the type: 您可以告诉Typescript返回的布尔值指示类型:

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

docs 文档

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

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