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?
You're looking for Typescript's Index Signature.
type Edge = {
name: string;
}
type Graph = {
edges: { [key: string]: Edge };
}
Choose simplicity by using the utility type Record<Keys, Type>:
type YourObjectType = {
edges: Record<string, { name: string }>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With