0

我有以下接口:

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

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

以及功能组件内部的状态,如下所示:

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

在代码中的某处,我试图动态访问属性的嵌套属性之一answersCount。我这样做的方式是:

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

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

无论我如何编写代码,我都会收到以下我无法摆脱的错误:

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

我无法弄清楚我做错了什么,非常感谢任何帮助。

4

3 回答 3

1

您正在索引错误的状态属性:(state.answerOptions这是一个数组)而不是state.answersCount.

我认为你的意思是:

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

或者,没有断言:

const doSomething = (answer: keyof IAnswersCount): void => {
  // other things happen here
  const value = state.answersCount[answer]
}
于 2021-05-01T23:38:13.343 回答
1

有2个问题:

  1. 您应该为“答案”使用更窄的类型
  2. 我认为您想使用answersCountnot answerOptions,因为answerOptions在您的示例中是一个数组AnswerType,而不是具有字符串属性的对象
const doSomething = (answer: keyof IAnswersCount): void => {

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

如果您确实打算使用answersOptions,请分享AnswerType.

于 2021-05-01T23:38:50.397 回答
0

您需要映射您的密钥,我编辑您的界面:

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

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

于 2021-05-01T23:24:15.157 回答