3

我有这样的数据示例,我收到:

{
  Europe: {
    WestEurope: {
      Belgium: [French, English, Dutch]
   }
  }
}

不知道如何为这样的动态结构创建接口,其中我有一棵树:

对象->对象(区域)->对象(子区域)->对象(国家)->ArrayOfStrings(语言)

我试过这样:

export interface Localisation {
    [key: string]: Localisation;
}
export interface Region {
    [key: string]: Region;
}
export interface SubRegion {
    [key: string]: SubRegion;
}
export interface Country {
    [key: string]: Country;
}
export interface Language {
    [index: number]: Array<string>;
}

但它们不是“链式”-> 所以“本地化”不知道它包含“区域”等。我想以某种方式连接它们。可能吗?

4

2 回答 2

2

这个怎么样?

interface Country {
  [proporty: string]: string[];
}

interface SubRegion {
  [property: string]: Country;
}

interface Region {
  [property: string]: SubRegion;   
}

interface Localisation {
  [property: string]: Region;
}
于 2019-06-17T12:17:07.033 回答
0

另一种方法是不使用单独的接口,而是将所有内容嵌套在一个接口下。这仅在您不需要单独的类型时才有效。

interface Localization {
    [region: string]: {
        [subregion: string]: {
            [country: string]: string[]
        }
    }
}


// Usage

const data: Localization = {
    Europe: {
        WestEurope: {
            Belgium: ['French', 'English', 'Dutch']
        }
    }
};

const westEurope = data['Europe']['WestEurope']; // Is of type { [country: string]: string[] }

于 2019-06-17T12:19:53.280 回答