【问题标题】:Type because expression of type 'any' can't be used to index type类型,因为类型 \'any\' 的表达式不能用于索引类型
【发布时间】:2022-10-23 19:35:02
【问题描述】:

如何摆脱这个打字稿错误(元素隐式具有“任何”类型,因为“任何”类型的表达式不能用于索引类型)?我试图在这两个中添加任何内容,即使那没有帮助。 Nullish 合并运算符使其更复杂,有什么建议吗?

const bookType:any = books.find(
    (book: any) => book.identifier === props.book?.identifier
  )?.type;

  const bookTypes:any = {
    "Fantasy": ["HarryPotter", "LordOfTheRings"],
    "Horror": ["Scream", "Men"],
   
  }[bookType] ?? ["Narnia", "Samaritan"];

【问题讨论】:

  • 停止使用任何,它将修复所有错误
  • @KonradLinkowski 仍然没有任何错误
  • 我对此表示怀疑。 books 的类型是什么?
  • @KonradLinkowski 任意(鼠标悬停)
  • 你必须确保没有任何东西是any 或者会有这样的错误

标签: javascript html reactjs typescript error-handling


【解决方案1】:

对于那些正在考虑我如何解决它的人(使用 Record<Keys, Type> 解决它):

const bookType:any = books.find(
    (book: any) => book.identifier === props.book?.identifier
  )?.type;

  const bookTypes:any =( {
    "Fantasy": ["HarryPotter", "LordOfTheRings"],
    "Horror": ["Scream", "Men"],
   
  }as Record<string, string[]> )[bookType] ?? ["Narnia", "Samaritan"];

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2021-12-24
    • 2022-10-08
    • 2021-10-24
    • 2020-11-14
    • 1970-01-01
    • 2021-11-11
    • 2022-08-17
    • 2022-11-10
    相关资源
    最近更新 更多