[英]Typescript Access objects nested within other types
I am relatively new to typescript and it's ins and outs and I am having trouble with a certain structure. 我对打字稿比较陌生,它来来往往,我在某种结构上遇到麻烦。 it looks like this: 它看起来像这样:
I have a function I am using to feed data to a timeline component. 我有一个用于将数据馈送到时间轴组件的函数。 the data recieved by the function can be of type 1 or type 2. Now this is where it gets complicated type 1 is a an object. 该函数接收的数据可以是类型1或类型2。现在这很复杂,类型1是一个对象。 However, type 2 can be any 1 of 4 different types 但是,类型2可以是4种不同类型中的任何一种
type1 : {} 类型1:{}
type2 : type3 | type2:type3 | type4 | type4 | type5 | type5 | type6 TYPE6
types 3-6 differ slightly in structure from one another and cannot be combined. 类型3-6的结构略有不同,无法合并。 In the function below the isConversion flag is a check for an (object: type6). 在isConversion标志下面的函数中,检查(object:type6)。 This object has another object inside it of type 7. 该对象内部有另一个类型为7的对象。
type 6: {
...,
type7: {
...,
conversions
}
}
inside type7 is a field called conversions that has the data I need to pass to the timeline. 在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
}
}
I have a work around where I fetch type7 when I get the data and set it to the state. 我有一个解决方法,当我获取数据并将其设置为状态时,在哪里获取type7。 and use that value but I would like to to know if there is a way to get the conversions object as above. 并使用该值,但是我想知道是否有一种获取上述转化对象的方法。
Thank You. 谢谢。
So you want to know if you can determine if items
type is Type6
? 因此,您想知道是否可以确定items
类型是否为Type6
?
Typescript types are lost after compilation so you have to write your own typeguard which will return true
if object is Type6
. 编译后Typescript类型会丢失,因此您必须编写自己的Typeguard,如果object是Type6
,它将返回true
。 It's pure javascript check, for example if you know that only Type6
has certain field you can check if it is present in this object. 这是纯JavaScript检查,例如,如果您知道只有Type6
具有特定字段,则可以检查它是否存在于此对象中。
interface Type6 {
comments: any[];
type6: Type7;
}
interface Type7 {
conversions: any[];
}
function isType6(obj): obj is Type6 {
return obj.type6 !== undefined;
}
Then you can use this typeguard like this: 然后,您可以像下面这样使用此类型保护程序:
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.