Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
Felipe César Avatar asked Oct 17 '25 11:10

Felipe César


2 Answers

[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

like image 150
Samathingamajig Avatar answered Oct 20 '25 00:10

Samathingamajig


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.

like image 23
captain-yossarian Avatar answered Oct 19 '25 23:10

captain-yossarian