簡體   English   中英

為什么 Typescript 不允許我使用括號表示法訪問 object 的屬性?

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

我有以下接口:

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

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

和一個功能組件內部的 state,如下所示:

 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'.

我無法弄清楚我做錯了什么,非常感謝任何幫助。

您需要 map 您的密鑰,我編輯您的界面:

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

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

您正在索引錯誤的 state 屬性: 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]
}

有2個問題:

  1. 您應該為“答案”使用更窄的類型
  2. 我認為您想使用answersCount而不是answerOptions ,因為answerOptions在您的示例中是AnswerType數組,而不是具有字符串屬性的 object
const doSomething = (answer: keyof IAnswersCount): void => {

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

如果您確實打算使用answersOptions ,請分享AnswerType的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM