我是Typescript的新手,并且有一个JSON对象,如下所示。我想将下面的对象映射到泛型 界面如下,但我确定那是不正确的。帮助我构造一个可以处理下面映射的通用接口/类。
"parentValue": {
"childValue1": {
"resource": "childValue1",
"application": "childValue1",
"permissions": [
"READ"
],
"attributeConstraints": {},
"attributeConstraintsCount": 0
},"childValue2": {
"resource": "childValue2",
"application": "childValue2",
"permissions": [
"READ"
],
"attributeConstraints": {},
"attributeConstraintsCount": 0
},
"childValue3": {
"resource": "childValue3",
"application": "childValue3",
"permissions": [
"READ"
],
"attributeConstraints": {},
"attributeConstraintsCount": 0
}
}
interface ParentValue{
childValue: ChildValue<T>
}
export interface ChildValue<T>{
childDetails: ChildDetails
}
export ChildDetails{
resource: string;
application: string;
permissions: string[];
attributeConstraints: AttributeConstraints;
attributeConstraintsCount: number;
}
答案 0 :(得分:1)
您的情况没有通用的。只需这样写:
export ChildDetails {
resource: string;
application: string;
permissions: string[];
attributeConstraints: AttributeConstraints;
attributeConstraintsCount: number;
}
interface ParentValue {
childValue1: ChildDetails,
childValue2: ChildDetails,
childValue3: ChildDetails,
}
如果childValueX
的数量不受限制,那么您将无法做得更好:
interface ParentValue {
[key: string]: ChildDetails
}
但是您不能告诉编译器key
看起来像childValue\d+
。