Typescript 中对象的对象的接口结构
Interface structure in Typescript for object of objects
从服务器接收到的JSON的结构是这样的(我更改了细节):
{
"apple": {
"fruitName": "apple",
"types": {
"greenApple": {
"productCode": "P1",
"productName": "Green Apple",
"color": "green",
},
"galaApple": {
"productCode": "P2",
"productName": "Gala Apple",
"color": "light red",
},
"redDelicious": {
"productCode": "P3",
"productName": "Red delicious apple",
"color": "bright red",
}
}
},
"orange": {
"fruitName": "orange",
"types": {
"mandarin": {
"productCode": "P5",
"productName": "Mandarin Oranges",
"color": "orange",
},
"bloodOrange": {
"productCode": "P6",
"productName": "Blood Orange",
"color": "red",
}
}
},
}
我正在为我的项目设计一个使用 Typescript 的接口结构。
到目前为止我已经想到了这个:
export type FruitTypes = {
[key: string]: Product,
}
export type Product = {
productCode: string
productName: string
color: string
}
export type Fruits = {
fruitName: string
type: object<FruitTypes>
}
我不明白的是如何在 Fruits 中声明类型?
type: object<FruitTypes>
无效。它将成为对象的对象。我们如何在 Typescript 中描述它。
我更喜欢用Record<K,T>
export type Fruits = Record<string, FruitTypes>;
export type FruitTypes = {
fruitName: string;
types: Record<string, Product>;
}
export type Product = {
productCode: string;
productName: string;
color: string;
}
或者你可以明确地写出来
export type Fruits = {
[key:string]: FruitTypes;
}
export type FruitTypes = {
fruitName: string;
types: {
[key:string]: Product;
};
}
export type Product = {
productCode: string;
productName: string;
color: string;
}
其中 Fruits
是整个结构的类型。
从服务器接收到的JSON的结构是这样的(我更改了细节):
{
"apple": {
"fruitName": "apple",
"types": {
"greenApple": {
"productCode": "P1",
"productName": "Green Apple",
"color": "green",
},
"galaApple": {
"productCode": "P2",
"productName": "Gala Apple",
"color": "light red",
},
"redDelicious": {
"productCode": "P3",
"productName": "Red delicious apple",
"color": "bright red",
}
}
},
"orange": {
"fruitName": "orange",
"types": {
"mandarin": {
"productCode": "P5",
"productName": "Mandarin Oranges",
"color": "orange",
},
"bloodOrange": {
"productCode": "P6",
"productName": "Blood Orange",
"color": "red",
}
}
},
}
我正在为我的项目设计一个使用 Typescript 的接口结构。
到目前为止我已经想到了这个:
export type FruitTypes = {
[key: string]: Product,
}
export type Product = {
productCode: string
productName: string
color: string
}
export type Fruits = {
fruitName: string
type: object<FruitTypes>
}
我不明白的是如何在 Fruits 中声明类型?
type: object<FruitTypes>
无效。它将成为对象的对象。我们如何在 Typescript 中描述它。
我更喜欢用Record<K,T>
export type Fruits = Record<string, FruitTypes>;
export type FruitTypes = {
fruitName: string;
types: Record<string, Product>;
}
export type Product = {
productCode: string;
productName: string;
color: string;
}
或者你可以明确地写出来
export type Fruits = {
[key:string]: FruitTypes;
}
export type FruitTypes = {
fruitName: string;
types: {
[key:string]: Product;
};
}
export type Product = {
productCode: string;
productName: string;
color: string;
}
其中 Fruits
是整个结构的类型。