0

I want to create a type that represents an object with a defined number of entries. Both key and the value should be of type number. In theory, I would like to have something like this:

type MatchResult = {
  [key: number]: number;
  [key: number]: number;
}

The above type represents a match result of 2 teams where the key is the team id and the value is the number of scored goals (this is a good example of usage of such type).

The example above gives an error - you can't define multiple index types.

vlio20
  • 8,955
  • 18
  • 95
  • 180
  • Does this answer your question? [Type dynamic keys with max number of properties in typescript](https://stackoverflow.com/questions/72182781/type-dynamic-keys-with-max-number-of-properties-in-typescript) – Tobias S. Jun 10 '22 at 07:27
  • This isn't something the language officially supports. In the link above you can find some solutions to the problem. – Tobias S. Jun 10 '22 at 07:28

1 Answers1

0

If you don't know the keys before hand then they can be any number, this means that a:

type MatchResult = {
 [key: number]: number
}

will work.

If you know the keys before hand you can do something like this:

type MatchResult = {
 111: number,
 222: number
}

This will allow access like: a[111], but not a[232] where a is of type MatchResult.

But if you want to have a type that has exactly 2 integer keys I don't think that's possible in TS. For one thing it would need to track each object of type MatchResult contextually.

You are better off declaring a more specific type, something like this:

type TeamResult {
 id: number;
 result: number;
}

type MatchResult {
 host: TeamResult;
 guest: TeamResult;
}
Radu Diță
  • 13,476
  • 2
  • 30
  • 34