首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >元素具有“任意”类型,因为类型为“string”的表达式。

元素具有“任意”类型,因为类型为“string”的表达式。
EN

Stack Overflow用户
提问于 2020-05-27 14:15:06
回答 3查看 452关注 0票数 0

为什么我会有这个错误?

代码语言:javascript
运行
复制
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变量给了我这个红旗。

代码语言:javascript
运行
复制
 const getStatusMeaning = (index: string) => {
    const StatusMap = {
      '0': 'Unknown',
      '1': 'Pending',
      '2': 'Success',
      '3': 'Failure',
    }

    return StatusMap[index]
  }
EN

Stack Overflow用户

回答已采纳

发布于 2020-05-27 14:25:21

作为@Paleo答案的另一种选择,如果您想要一个强类型的方法,我建议如下:

代码语言:javascript
运行
复制
const StatusMap = {
  '0': 'Unknown',
  '1': 'Pending',
  '2': 'Success',
  '3': 'Failure',
};

const getStatusMeaning = (index: keyof typeof StatusMap): string => {
  return StatusMap[index];
}

票数 2
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62045276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档