Home > other >  Interface with defined number of entries in typescript
Interface with defined number of entries in typescript

Time:06-10

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.

CodePudding user response:

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;
}
  • Related