Home > OS >  Typescript generics unlimited nested object
Typescript generics unlimited nested object

Time:09-20

Trying to define a type/interface for a structure of unlimited nested objects but its value must be number|number[].

type TValue = number | number[];
type TDataLevel1 = {
  [key: string]: TValue;
};
type TDataLevel2 = {
  [key: string]: TValue | TDataLevel1;
};
type TData = {
  [key: string]: TValue | TDataLevel2;
};

This works up to 3 levels of nested objects. However, the JSON path .key2.key2.key2.key1 has error since it is the 4th level.

  let data: TData = {
    key1: 1234,
    key2: {
      key1: [2, 4],
      key2: {
        key1: [6, 8],
        key2: { key1: [10, 12, 14] },  // error here
      },
    },
  };

This can be resolved by adding more boilerplate TDataLevel3,4..,N to support N levels. Is there any better way to define such kind of data?

CodePudding user response:

We can simply reference the type recursively:

type TDataB = {
  [key: string]: TValue | TDataB;
};

Playground Link

  • Related