I'm building an application that access an API that returns an object with many unknown keys, each key represents an id of a user.
Example:
const response = {
"random id1": {name: "user1"},
"random id2": {name: "user2"},
...
"random id100": {name: "user100"}
}
I know that if I have just one unknown key I can define using something like:
type MyDefinition = {
[key: string]: Metadata
}
But how can I define an object with so many different keys?
CodePudding user response:
You can use a type defined with a template string like this:
const response: { [key: `random id${number}`]: { name: string }} = {
"random id1": {name: "user1"},
"random id2": {name: "user2"},
"random id100": {name: "user100"}
}
You can see it in action on this
Here and here you can find an explanation of number range.
You have probable noticed that there is a limit you can't cross.
With above approach it will not allow random id1e4
.