如何解决打字稿/反应错误TS7053?

时间:2020-09-22 08:51:02

标签: reactjs typescript

我遇到一个错误: TS7053:元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型“ {{name:string; isLandlocked:布尔值; }'。在类型'{{name: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>

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

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

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'}
}