[英]Typescript Access objects nested within other types
我对打字稿比较陌生,它来来往往,我在某种结构上遇到麻烦。 它看起来像这样:
我有一个用于将数据馈送到时间轴组件的函数。 该函数接收的数据可以是类型1或类型2。现在这很复杂,类型1是一个对象。 但是,类型2可以是4种不同类型中的任何一种
类型1:{}
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。 并使用该值,但是我想知道是否有一种获取上述转化对象的方法。
谢谢。
因此,您想知道是否可以确定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;
}
然后,您可以像下面这样使用此类型保护程序:
if(isType6(items)) {
const {comments, type6: {conversions}} = items; // no cast needed, ts know it is Type6
return {comments, conversions };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.