简体   繁体   中英

Why won't Typescript let me access the property of an object using bracket notation?

I have the following interfaces:

interface IAnswersCount {
  nintendo: number;
  microsoft: number;
  sony: number;
}

interface IState {
  counter: number;
  questionId: number;
  question: string;
  answerOptions: AnswerType[];
  answer: string;
  answersCount: IAnswersCount;
  result: string;
}

and a state inside of a functional component, written like so:

 const [state, setState] = React.useState<IState>({
    counter: 0,
    questionId: 1,
    question: '',
    answerOptions: [],
    answer: '',
    answersCount: {
      nintendo: 0,
      microsoft: 0,
      sony: 0,
    },
    result: '',
  });

Somewhere in the code I am trying to dynamically access one of the nested properties of the answersCount property. The way I am doing it is like:

const doSomething = (answer: string): void => {

// other things happen here
   const value = state.answerOptions[answer as keyof IAnswersCount]
}

I get the following error which I can't rid of, no matter how I write the code:

Element implicitly has an 'any' type because index expression is not of type 'number'.

I can't figure it out what I am doing wrong, any help is much appreciated.

You need to map your key, i edit your interface:

interface IAnswersCount {
  [key: string]: number,
  nintendo: number;
  microsoft: number;
  sony: number;
}

// [key: string]: number
// is not a new property, is a map access definition

You're indexing the wrong state property: state.answerOptions (which is an array) instead of state.answersCount .

I think you mean to do:

const doSomething = (answer: string): void => {
  // other things happen here
  const value = state.answersCount[answer as keyof IAnswersCount]
}

or, without the assertion:

const doSomething = (answer: keyof IAnswersCount): void => {
  // other things happen here
  const value = state.answersCount[answer]
}

There's 2 problems:

  1. You should use a narrower type for 'answer'
  2. I think you want to use answersCount not answerOptions , because answerOptions is in your example an array of AnswerType , not an object with string properties
const doSomething = (answer: keyof IAnswersCount): void => {

   // other things happen here
   const value = state.answersCount[answer];
}

If you did mean to use answersOptions , share the type of AnswerType .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM