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

Ser*_*aev 0 typescript

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

const nestedDictionary = {
   a: {
     b: true
   },
   c: true,
   d: {
     e: {
       f: true
     }
   }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

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

const nestedDictionary: Dictionary;
Run Code Online (Sandbox Code Playgroud)

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

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

const nestedDictionary: GenericDictionary<boolean>;
Run Code Online (Sandbox Code Playgroud)