如何将通用对象映射到打字稿类

时间:2019-12-18 09:30:29

标签: typescript

我是Typescript的新手,并且有一个JSON对象,如下所示。我想将下面的对象映射到泛型 界面如下,但我确定那是不正确的。帮助我构造一个可以处理下面映射的通用接口/类。

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;
}

1 个答案:

答案 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+