【发布时间】: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