简体   繁体   中英

Typescript generics unlimited nested object

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?

We can simply reference the type recursively:

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

Playground Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM