Home > Software design >  There is a better ways to write generics in nested objects in typescript
There is a better ways to write generics in nested objects in typescript

Time:03-25

I have an object with a lot of nested objects with this structure:

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

Which is the best way to write it cleaner, without a lot of type repetitions in Typescript?

CodePudding user response:

You can do something like this

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;
            };
        };
    };
}

This works using condtionals and recursion. We simply have a recursive type, which we append a tuple to each layer deeper we go, and then once we hit the desired depth we stop.

See it on TS Playground

  • Related