如何在打字稿中定义嵌套字典类型

时间:2021-05-14 14:01:32

标签: typescript

我正在努力为具有如下嵌套结构的对象定义类型:

const nestedDictionary = {
   a: {
     b: true
   },
   c: true,
   d: {
     e: {
       f: true
     }
   }
}

1 个答案:

答案 0 :(得分:3)

type Dictionary = {
  [x: string]: boolean | Dictionary;
};

const nestedDictionary: Dictionary;

或者,如果您更喜欢使用类型作为参数:

type GenericDictionary<T> = {
  [x: string]: T | GenericDictionary<T>;
};

const nestedDictionary: GenericDictionary<boolean>;