Home > other >  TypeScript: type with list of properties based on the same pattern
TypeScript: type with list of properties based on the same pattern

Time:11-20

I want to have a type that can include any number of properties based on a predefined pattern like this:

type Values = {
  id: number;
  id1?: number;
  id2?: number;
  id2?: number;
  id3?: number;
  id4?: number;
  id5?: number;
  // ...
  somethingElse: string;
  anotherOne: number;
};

But because I don't exactly know how many ids there are, I thought that there is may something like this:

// pseudo-code
type Values = {
  id: number;
  [`id${index}`?: number];
  somethingElse: string;
  anotherOne: number;
};

So I don't have to use [k: string]: number.

If there is not such a way, what would be the easiest/best way to achieve something similar without just adding a random (very high) amount of idX properties

  • Related