Felipe César
Felipe César

Reputation: 1444

Typescript: how to define a object with many unknown keys

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?

Upvotes: 3

Views: 3337

Answers (3)

Samathingamajig
Samathingamajig

Reputation: 13243

[key: string] allows for any amount of unique strings as keys.

type Metadata = {
  name: string
}

type MyDefinition = {
  [key: string]: Metadata
}

const response: MyDefinition = {
  "random id1": {name: "user1"},
  "random id2": {name: "user2"},
  // ...
  "random id100": {name: "user100"},
};

Try it on TypeScript Playground

Upvotes: 5

Extending @ASDFGerte comment. You can generate a range of numbers from 0 to 998 in typescript 4.5:


type MAXIMUM_ALLOWED_BOUNDARY = 999

type ComputeRange<
  N extends number,
  Result extends Array<unknown> = [],
  > =
  (Result['length'] extends N
    ? Result
    : ComputeRange<N, [...Result, Result['length']]>
  )

// 0 , 1, 2 ... 998
type NumberRange = ComputeRange<MAXIMUM_ALLOWED_BOUNDARY>[number]

type Name<T extends string> = { name: T }

type CustomResponse = {
  [Prop in NumberRange]: Record<`random id${Prop}`, Name<`id${Prop}`>>
}


Playground

enter image description here

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.

Upvotes: 4

Guerric P
Guerric P

Reputation: 31815

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 TypeScript playground.

Upvotes: 2

Related Questions