Billy Adelphia
Billy Adelphia

Reputation: 1027

Typescript how to write nested object types with non-static keys

I have an object like this, lets call theObject variable

         {
            "activate": {
                "from": "pending",
                "to": "active"
            },
            "deactivate": {
                "from": ["pending", "active"],
                "to": "inactive"
            }
        };

and example code like this

class Test {
   constructor(data : Object)
}

const test = new Test(theObject);

The code isn't returning any error since the type is correct. But I want more deep type interface for theObject. The list of objects within theObject can be anything and more, like this for example :

{
            "darkKnight": { // the key should be in string
                "from": "bruceWayne", // from should be string or array of string
                "to": "batman" // to should be string
            },
            "theAmazing": {
                "from": ["peterParker", "milesMorales"],
                "to": "spiderMan"
            },
            "manOfSteel": {
                "from": "clackKent",
                "to": "superman"
            }
        };

The question is, how to write the more deep type definition interface for theObject, rather than using Object type

Upvotes: 0

Views: 77

Answers (1)

user13258211
user13258211

Reputation:

Based on your samples a fitting interface could look somewhat like this:

interface ObjectType {
    [key: string]: { from: string | string[]; to: string; }
}

Playground

Upvotes: 1

Related Questions