我是一个比较新的打字员,它是进进出出的,我在某种结构上遇到了麻烦。它看起来是这样的:
我有一个函数,我正在使用它向时间轴组件提供数据。该函数接收的数据可以是类型1或类型2。现在它变得复杂了,类型1是一个对象。但是,类型2可以是4种不同类型中的任意一种
type1:{}
type2 : type3 | type4 | type5 | type6
类型3-6在结构上彼此略有不同,不能组合。在isConversion标志下面的函数中,是对(object: type6)的检查。此对象中有另一个类型为7的对象。
type 6: {
...,
type7: {
...,
conversions
}
}在type7内部有一个名为conversions的字段,其中包含我需要传递给时间线的数据。
timelineItems = (items: type1 | type2): PropsData => {
const { dataType, isConversion } = this.state
if(isConversion){
const {comments, type7.conversions } = items as type6
return {
comments
type7.conversions
}
}我有一个解决办法,就是在获取数据并将其设置为状态时获取type7。并使用该值,但我想知道是否有方法可以如上所述获得转换对象。
谢谢。
发布于 2019-03-18 07:05:46
因此您想知道是否可以确定items类型是否为Type6
Typescript类型在编译后丢失,因此您必须编写自己的typeguard,如果object为Type6,它将返回true。它是纯javascript检查,例如,如果你知道只有Type6有特定的字段,你可以检查它是否出现在这个对象中。
interface Type6 {
comments: any[];
type6: Type7;
}
interface Type7 {
conversions: any[];
}
function isType6(obj): obj is Type6 {
return obj.type6 !== undefined;
} 然后你可以像这样使用这个typeguard:
if(isType6(items)) {
const {comments, type6: {conversions}} = items; // no cast needed, ts know it is Type6
return {comments, conversions };
}https://stackoverflow.com/questions/55210516
复制相似问题