为什么我会有这个错误?
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ 0: string; 1: string; 2: string; 3: string; }'.
No index signature with a parameter of type 'string' was found on type '{ 0: string; 1: string; 2: string; 3: string; }'.ts(7053)
这是我的代码:我专门为索引设置了一个字符串,所以应该没有问题,但是我的StatusMap变量给了我这个红旗。
const getStatusMeaning = (index: string) => {
const StatusMap = {
'0': 'Unknown',
'1': 'Pending',
'2': 'Success',
'3': 'Failure',
}
return StatusMap[index]
}
发布于 2020-05-27 14:25:21
作为@Paleo答案的另一种选择,如果您想要一个强类型的方法,我建议如下:
const StatusMap = {
'0': 'Unknown',
'1': 'Pending',
'2': 'Success',
'3': 'Failure',
};
const getStatusMeaning = (index: keyof typeof StatusMap): string => {
return StatusMap[index];
}
发布于 2020-05-27 14:21:57
您可以为index
定义合适的类型:
const getStatusMeaning = (index: '0' | '1' | '2' | '3') => {
// Your implementation here
}
或者,使用字典类型 { [key: string]: string }
const getStatusMeaning = (index: string) => {
const StatusMap: { [key: string]: string } = {
'0': 'Unknown',
'1': 'Pending',
'2': 'Success',
'3': 'Failure',
}
return StatusMap[index]
}
发布于 2020-05-27 14:24:01
如果将某些字符串不作为键存在于状态映射中,则可以让TypeScript知道您的映射是字符串记录:
const StatusMap: Record<string, string> = {
另一种解决方案是对索引更加具体,只允许支持的索引,而不是任何字符串。
https://stackoverflow.com/questions/62045276
复制相似问题