我想断言一个对象属性的类型,以消除由该属性具有联合类型引起的歧义。
interface myObject {
myProperty: customType1|customType2
}
//Now I want to make clear in some other line of code that i know what is
// The type of that property at that time, somthing like this
myObject.<customType1>myProperty
我四处搜寻,但找不到任何涉及这种情况的东西,有可能吗?
似乎执行此操作的方法是:
myObject.myProperty = myObject.myProperty as customType1
由于评论中的人,我今天发现了一些有趣的功能,但幸运的是,最终我变得很简单。
如Typescript文档中所述,https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types
首先,在父属性上声明类型,然后访问子属性
(<customType1>myObject.myProperty)
// or
(myObject.myProperty as customType1)
// if there is any child-property
(myObject.myProperty as customType1)['child_property_of_myproperty'];