I am building a card game and have the following types:
type Rank = "A"| "2"| "3"| "4"| "5"| "6"| "7"| "8"| "9"| "T"| "J"| "Q"| "K";
interface IPowerCards {
[key: Rank]: any
}
I also have the following object which I am trying to access with a rank string:
const powerCards: IPowerCards = {
"A": {
canPlayOnAnyCard: true,
canChangeSuit: true,
},
"2": {
canCounterPenaltyCard: true,
penaltyAmount: 2,
},
...,
};
All the keys on this object are valid Rank
types. I am trying to access values on the powerCards
object using the following code:
const rank = getRank(card) as Rank;
return rank && powerCards[rank]?.canCounterPenaltyCard
However, I get the error Element implicitly has an 'any' type because expression of type 'Rank' can't be used to index type 'IPowerCards'. Property 'A' does not exist on type 'IPowerCards'.
This error message doesn't make sense to me because I am ensuring that the rank
variable, which is the variable I am using to access the powerCards
object, is of Rank
type, which is what I have specified in my IPowerCards
type definition. Where am I going wrong? Thanks
CodePudding user response:
Use a Record
for IPowerCards
instead:
type IPowerCards = Record<Rank, any>
If you want to have the properties optional:
type IPowerCards = {
[key in Rank]?: any
}