[英]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.