我遇到一个错误: 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>
有人可以帮我吗?
答案 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'}
}