简体   繁体   中英

Typescript "Element implicitly has an 'any' type because expression of type 'Rank' can't be used to index type 'IPowerCards'"

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'. 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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM