我想寫打字稿
dynamicContent?: {
data?: {
attributes?: {
baccarat?: { title?: string | null; content?: string | null } | null;
baccaratOnline?: { title?: string | null; content?: string | null } | null;
casino?: { title?: string | null; content?: string | null } | null;
casinoOnline?: { title?: string | null; content?: string | null } | null;
games?: Array<{
gameUrl?: string | null;
media: {
data?: {
attributes?: {
url: string;
alternativeText?: string | null;
width?: number | null;
height?: number | null;
} | null;
} | null;
};
} | null> | null;
} | null;
} | null;
} | null;
};
我想在這里使用型別游戲是我嘗試的
Pick<NonNullable<GetDynamicContentQuery["dynamicContent"]["data"]["attributes"]>, 'games'>
似乎只能為空的動態內容欄位不確定如何全部為空
uj5u.com熱心網友回復:
您似乎不了解 optional 和 nullable 之間的區別,因此 和 之間的undefined區別null。
在 TypeScript 中,當您定義一個可選屬性時,它會有效地使其成為屬性的型別或undefined:
interface MyInterface {
myField?: number;
}
將與以下內容有效相同:
interface MyInterface {
myField: number | undefined;
}
現在,讓我們談談null和undefined。在 JavaScript(在其之上構建 TypeScript)中,undefined意味著某些東西不存在。當物件的屬性不存在時使用它:
const obj = { prop1: 'Prop 1', prop2: 'Prop 2', prop3: 123 };
console.log(obj.prop1); // 'Prop 1'
console.log(obj.prop2); // 'Prop 2'
console.log(obj.prop3); // 123
console.log(obj.prop4); // undefined
另一方面,我們有null. null是 JavaScript 中的實際值,就像任何數字、字串、物件或函式一樣。它用于標識屬性/變數,持有值本身存在,但值什么都不是。
允許null在 TypeScript 中存在可選屬性會導致問題出現,因此建議您不要這樣做,而只需將屬性設為可選即可。
盡管如此,這已經得到了解釋,而且比我做的要好得多:https ://stackoverflow.com/a/57249968/10566045
uj5u.com熱心網友回復:
@TopchetoEU 的回答是正確的,您可能應該以interface GetDynamicContentQuery不同的方式定義。但是如果你由于某種原因不能改變定義,這里有一個games無論如何都可以訪問的解決方案:
type DeeplyRemoveNullAndOptional<T> = {
[K in keyof T]-?: Exclude<T[K], null | undefined> extends Record<any, any>
? DeeplyRemoveNullAndOptional<Exclude<T[K], null>>
: NonNullable<T[K]>
}
type GamesType = DeeplyRemoveNullAndOptional<
GetDynamicContentQuery
>["dynamicContent"]["data"]["attributes"]["games"]
我很困惑為什么你甚至需要Pick. 您可以直接訪問games。
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477931.html
標籤:打字稿
下一篇:如何將字串陣列轉換為數字陣列?
