繁体   English   中英

Typescript “元素隐式具有‘any’类型,因为类型‘Rank’的表达式不能用于索引类型‘IPowerCards’”

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

我正在构建纸牌游戏并具有以下类型:

type Rank = "A"| "2"| "3"| "4"| "5"| "6"| "7"| "8"| "9"| "T"| "J"| "Q"| "K";

interface IPowerCards {
  [key: Rank]: any
}

我还有以下 object,我正在尝试使用排名字符串访问它:

const powerCards: IPowerCards = {
  "A": {
    canPlayOnAnyCard: true,
    canChangeSuit: true,
  },
  "2": {
    canCounterPenaltyCard: true,
    penaltyAmount: 2,
  },
  ...,
};

这个 object 上的所有键都是有效的Rank类型。 我正在尝试使用以下代码访问powerCards object 上的值:

const rank = getRank(card) as Rank;
return rank && powerCards[rank]?.canCounterPenaltyCard

但是,我收到错误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'. 此错误消息对我来说没有意义,因为我确保rank变量(我用来访问powerCards object 的变量)属于Rank类型,这是我在IPowerCards类型定义中指定的。 我哪里错了? 谢谢

改用IPowerCardsRecord

type IPowerCards = Record<Rank, any>

如果你想让属性可选:

type IPowerCards = {
  [key in Rank]?: any
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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