有更好的方法可以在打字稿的嵌套对象中编写泛型

There is a better ways to write generics in nested objects in typescript

我有一个对象,其中包含很多具有这种结构的嵌套对象:

    type itemType = {
  [key: string]: {
    [key: string]: { [key: string]: { [key: string]: string } };
  };
};

在 Typescript 中没有大量类型重复的最佳编写方式是什么?

你可以这样做

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

上查看