Devansh
Devansh

Reputation: 193

How to map generic objects to a typescript class

I'm new to typescript and I have a JSON object as below. I want to map below object to a generic interface as below, but I'm sure that's incorrect. Help me constructing a generic interface/class which can handle below mapping.

JSON Object

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

}

Typescript Interface

interface ParentValue{
   childValue: ChildValue<T>
}

export interface ChildValue<T>{
  childDetails: ChildDetails
}

export ChildDetails{
 resource: string;
  application: string;
  permissions: string[];
  attributeConstraints: AttributeConstraints;
  attributeConstraintsCount: number;
}

Upvotes: 1

Views: 148

Answers (1)

Alexandre Annic
Alexandre Annic

Reputation: 10788

There is nothing generic in your case. Simply write something like that:

export ChildDetails {
  resource: string;
  application: string;
  permissions: string[];
  attributeConstraints: AttributeConstraints;
  attributeConstraintsCount: number;
}

interface ParentValue {
  childValue1: ChildDetails,
  childValue2: ChildDetails,
  childValue3: ChildDetails,
}

If you have an unlimited number of childValueX there is nothing you can do better than:

interface ParentValue { 
  [key: string]: ChildDetails 
}

But you can't tell to the compiler that key looks like childValue\d+.

Upvotes: 1

Related Questions