我有一個物件,其中包含許多具有這種結構的嵌套物件:
type itemType = {
[key: string]: {
[key: string]: { [key: string]: { [key: string]: string } };
};
};
在 Typescript 中沒有大量型別重復的情況下,哪種方式可以更簡潔地撰寫它?
uj5u.com熱心網友回復:
你可以做這樣的事情
type itemNode<D, Depth extends any[] = []> =
Depth extends {length: D}
? never //Stop when we hit desired depth
: {
[index: string]: itemNode<D, [...Depth, true]>
}
type testItem = itemNode<4>
//=>
type testItem = {
[index: string]: {
[index: string]: {
[index: string]: {
[index: string]: never;
};
};
};
}
這使用條件和遞回。我們只是有一個遞回型別,我們將一個元組附加到我們深入的每一層,然后一旦我們達到所需的深度,我們就會停止。
在TS Playground上看到
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/449559.html
上一篇:型別被注釋時打字稿映射型別錯誤
