Search code examples
typescripttypesjavascript-objectstypescript-typings

Defining object type without knowing properties keys in TypeScript


I want to define an object type in TypeScript, that is composed of several properties of which I want to define the type, but without knowing them keys.

I could have used an array to filter, but I prefer to use properties to gain speed (my use case is a graph).

Ex:

{
    "edges": {
        "bc73c36e-db11-4020-bef9-9ba5ffe2d6d4": {
            "name": "John"
        },
        "0691e3c2-7c69-4ec8-8e59-6b0055855a38": {
            "name": "Mike"
        },
        "6f0ca8f0-d595-4cc2-a62f-adfe35ba4808": {
            "name": "Lucy"
        },
        ...
    }
}

How can I define this object type of edges in TypeScript?


Solution

  • You're looking for Typescript's Index Signature.

    type Edge = {
      name: string;
    }
    
    type Graph = {
      edges: { [key: string]: Edge };
    }