我第一天用 React + TS 构建东西。
我正在尝试使用“字典”将字符串转换为另一个字符串。
import { eventDictionary } from '../utils/eventDictionary'
type Props = {
id: string
type: string
}
const GameCard: React.FC<Props> = ({id, type}) => {
return (
<div key={id}>
<h3>{eventDictionary[type]}</h3>
<h3>{type}</h3>
</div>
)
}
这是字典:
bsk: "basketball",
foot: "football",
tenn: "tennis"
}
但我得到:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ bsk: string; foot: string; tenn: string; }'.
No index signature with a parameter of type 'string' was found on type '{ bsk: string; foot: string; tenn: string; }'.
我究竟做错了什么?
将道具类型更改为明确地成为对象中的键。
type Props = {
id: string
type: 'bsk' | 'foot' | 'tenn'
}
如果事先不知道对象键,并且这样的解决方案不可用,我建议改用 Map。地图比 TypeScript 中的动态键控对象更容易操作。
import { eventDictionary } from '../utils/eventDictionary'
const eventMap = new Map(Object.entries(eventDictionary));
<h3>{eventMap.get(type)}</h3>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句