4

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?

2 Answers 2

5

You're looking for Typescript's Index Signature.

type Edge = {
  name: string;
}

type Graph = {
  edges: { [key: string]: Edge };
}
Sign up to request clarification or add additional context in comments.

Comments

1

Choose simplicity by using the utility type Record<Keys, Type>:

type YourObjectType = {
  edges: Record<string, { name: string }>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.