我在角度上有这个对象结构:
this.calendar = {
"years": {
2018: {
"months":
0: {
"weeks":
1: {
"days": {
1: {
date: "2018-05-01",
is_valid: true,
price: {'single': 21}
},
2: {
date: "2018-05-02",
is_valid: true,
price: {'single': 31}
},
3: {
date: "2018-05-03",
is_valid: true,
price: {'single': 231}
},
4: {
date: "2018-05-04",
is_valid: true,
price: {'single': 41}
}
}
},
2: {
"days": {
1: {
date: "2018-05-01",
is_valid: true,
price: {'single': 21}
},
...
}
},
},
1: {
"weeks":
...
},
...
},
2019: {
...
}
}
我想将此定义为模型中的接口,因为结构很可能保持不变(或将来会添加一些新东西)。
calendar.model.ts
export interface calendar {
...
}
是否有可能以某种有意义且易于理解的方式在模型中定义如此复杂的结构?
答案 0 :(得分:2)
您的界面可能如下所示:
interface calendar {
years: {
[year: number]: {
months: {
[month: number]: {
weeks: {
[week: number]: {
days: {
[day: number]: {
date: string,
is_valid: boolean,
price: {
[quantity: string]: number
}
}
}
}
}
}
}
}
}
}
我不知道是否还会有price
以外的其他single
,所以请随时进行相应的更改。
但是请注意,您发布的对象不是有效的JSON。我只是猜到了
"months":
0: {
缩写为
"months": {
0: {
等,因此这是有效的分配:
const data: calendar = {
"years": {
2018: {
"months": {
0: {
"weeks": {
1: {
"days": {
1: {
date: "2018-05-01",
is_valid: true,
price: { 'single': 21 }
},
2: {
date: "2018-05-02",
is_valid: true,
price: { 'single': 31 }
},
3: {
date: "2018-05-03",
is_valid: true,
price: { 'single': 231 }
},
4: {
date: "2018-05-04",
is_valid: true,
price: { 'single': 41 }
}
}
},
2: {
"days": {
1: {
date: "2018-05-01",
is_valid: true,
price: { 'single': 21 }
}
}
}
}
}
}
}
}
};
答案 1 :(得分:0)
我建议将声明分成较小的部分。如果您需要以较小的部分来构造数据(即增加一天的时间),这将变得更加容易。
export interface Calendar {
years: Year[];
}
export interface Year {
year: number;
months: Month[];
}
export interface Month {
month: number;
days: Day[];
}
export interface Day {
day: number
date: string;
is_valid: boolean;
price: {
single: number
}
}
然后可以按以下方式声明对象:
const data: Calendar = {
years: [{
year: 2018,
months: [{
month: 0,
days: [{
day: 1,
date: "2018-01-02",
is_valid: true,
price: { single: 21 }
}]
}]
}]
};