1

I got an error : TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; isLandlocked: boolean; }'.   No index signature with a parameter of type 'string' was found on type '{ name: string; isLandlocked: boolean; }'.

My code looks like:

//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>

Can somebody help me please ?

bacdor
  • 11
  • 1
  • https://stackoverflow.com/questions/35435042/how-can-i-define-an-array-of-objects Create type or use indexes with quotation marks when assigning value. – apincik Sep 22 '20 at 08:59
  • What do you mean by "create type" ? I thought I created the type here ```const questions: {name: string, quest: string}[]``` and here ```let questionValue: string``` – bacdor Sep 23 '20 at 07:02

1 Answers1

0

There seems to be something weird in your code.

questionValue is a string (e.g. isBlue) and questions is an array of {name: string, quest: string}. You are trying to access a position of questions array using a string, while the only indexing you have so far is numbers. In other words, you are trying to access something like questions['isBlue'] rather than questions[0].

If you want to create a string indexed, than you should create a type like the following:

type QuestionType = {[key: string]: {name: string, quest: string}}
const questions:  QuestionType = {
  'blue': {name: 'test', quest: 'thisQuest'}
}
Guilhermevrs
  • 2,094
  • 15
  • 15
  • Well, it steel does not work. The thing is my code does work when I do: ```this.setState(color=> ({colorsList: state.colorsList.filter((value) => !states[states.findIndex(element => element.name === value)]["isLandlocked"])})) }``` but the problem appears when I'm trying to use the variable ```questionValue``` (which is a string "isLandlocked") intesad of just a string ```"isLandlocked"```. This is why it is so confusing for me. I believe there is something wrong because it is my first time using typescript instead of javascript. – bacdor Sep 23 '20 at 06:58