【问题标题】:How do I solve typescript/react error TS7053?如何解决打字稿/反应错误 TS7053?
【发布时间】:2021-01-08 08:54:29
【问题描述】:

我收到一个错误: TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{名称:字符串; isLandlocked:布尔值; }'。在“{ name: string; 类型”上找不到带有“string”类型参数的索引签名; isLandlocked:布尔值; }'。

我的代码如下:

//some array

const questions: {name: string, quest: string}[] = [
    {name: "Is the square blue?",
      quest: "isBlue"}
  ]; //there's gonna be more elements in this array eventually

(...)
//my state
this.state = {
      colorsList: colors.map(value => (value.name)),
      questionIndex: Math.floor(Math.random() * questions.length),
    };
(...)
//handle click on answer button (let's say we always use "no")
handleAnswer() {

let questionValue: string = questions[this.state.questionIndex].quest;

this.setState(color=> ({colorsList: state.colorsList.filter((value) =>
   !states[states.findIndex(element => element.name === value)][questionValue])}))
  }
(...)
//the button
<button id="no" onClick={this.handleAnswer}>NO</button>

有人可以帮帮我吗?

【问题讨论】:

  • stackoverflow.com/questions/35435042/… 赋值时创建类型或使用带引号的索引。
  • “创建类型”是什么意思?我以为我在这里创建了类型 const questions: {name: string, quest: string}[] 和这里 let questionValue: string

标签: reactjs typescript


【解决方案1】:

您的代码中似乎有些奇怪。

questionValue 是一个字符串(例如isBlue),questions 是一个{name: string, quest: string} 的数组。您正在尝试使用字符串访问 questions 数组的位置,而到目前为止您唯一的索引是数字。换句话说,您正在尝试访问类似questions['isBlue'] 而不是questions[0]

如果你想创建一个被索引的字符串,那么你应该创建一个像下面这样的类型:

type QuestionType = {[key: string]: {name: string, quest: string}}
const questions:  QuestionType = {
  'blue': {name: 'test', quest: 'thisQuest'}
}

【讨论】:

  • 好吧,钢不行。问题是我的代码在我这样做时确实有效:this.setState(color=&gt; ({colorsList: state.colorsList.filter((value) =&gt; !states[states.findIndex(element =&gt; element.name === value)]["isLandlocked"])})) } 但是当我尝试使用变量questionValue(这是一个字符串“isLandlocked”)intesad 时出现问题,它只是一个字符串"isLandlocked"。这就是为什么它让我如此困惑。我认为有问题,因为这是我第一次使用 typescript 而不是 javascript。
猜你喜欢
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
相关资源
最近更新 更多