[英]how to access nested array type in typescript
我想從 typescript 的接口中提取一個子類型,如下所示
interface components {
schemas: {
a: {
b?: Array<{
c?: {
d?: string;
};
}>;
};
}
// I want to export
export type custom = components["schemas"]["a"]["b"][number]["c"]
但是我在[number]
處收到一條錯誤消息,說Type '{ c?: { d?: string | undefined; } | undefined; }[] | undefined' has no matching index signature for type 'number'.ts(2537)
Type '{ c?: { d?: string | undefined; } | undefined; }[] | undefined' has no matching index signature for type 'number'.ts(2537)
我們如何實現這一目標?
這是我想出的:
type Increment<A extends number[]> = [...A, 0];
type DeepRequired<T, D extends number = -1, R extends number[] = []> =
T extends object ? R["length"] extends D ? T : {
[K in keyof T]-?: DeepRequired<T[K], D, Increment<R>>;
} : T;
讓我們看看沒有額外位的DeepRequired
:
type DeepRequired<T> = T extends object ? {
[K in keyof T]-?: DeepRequired<T[K]>;
} : T;
這種類型的核心很簡單; 它只是遍歷整個 object 並使所有屬性成為必需的。
這確實可以正常工作:
type T = DeepRequired<components>["schemas"]["a"]["b"][number]["c"];
但是您會注意到T
的“d”屬性也是必需的,這可能不是所需的結果。 這就是為什么它要復雜得多; 它限制了它使屬性成為必需的深度。
回到我們原來的代碼片段,創建了一個實用程序類型Increment
來增加我們所在的深度, DeepRequired
的新參數包括指定的深度(可選)和它所在的當前深度。
在它要求所有屬性之前,它會檢查它是否超過了指定的深度,如果超出了,它就會停止。
這現在按預期工作:
type T = DeepRequired<components, 5>["schemas"]["a"]["b"][number]["c"];
我真的很喜歡@kellys對 DeepRequired 部分的回答,但是如果結果的目標是string | undefined
string | undefined
,我不喜歡必須對數字(深度)進行硬編碼的部分,因此我可以建議采用以下方法
type Path<T, K> = K extends [any, ...any]
? (K extends [keyof NonNullable<T>, ...infer RR]
? Path<NonNullable<T>[K[0]], RR>
: never)
: T
export type custom = Path<components, ['schemas', 'a', 'b', number, 'c', 'd']>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.