I have such example of data, that I receive:
{
Europe: {
WestEurope: {
Belgium: [French, English, Dutch]
}
}
}
Not sure how I can create an interface for such a dynamic structure, where I have a tree:
Object->Object(of Regions)->Object(of SubRegions)->Object(of Countries)->ArrayOfStrings(of languages)
I tried so:
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>;
}
but they aren't 'chained' -> so 'Localisation' doesn't know that it contains 'Regions' etc. And I want to connect them somehow. Is it possible?
How about this?
interface Country {
[proporty: string]: string[];
}
interface SubRegion {
[property: string]: Country;
}
interface Region {
[property: string]: SubRegion;
}
interface Localisation {
[property: string]: Region;
}
An alternative is not to use separate interfaces, but nest everything under one interface. This only works if you don't need the separate types though.
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[] }
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.