[英]Benefit of using bracket notation (with variables) to access a property of an 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個問題:
answersCount
而不是answerOptions
,因為answerOptions
在您的示例中是AnswerType
數組,而不是具有字符串屬性的 objectconst doSomething = (answer: keyof IAnswersCount): void => {
// other things happen here
const value = state.answersCount[answer];
}
如果您確實打算使用answersOptions
,請分享AnswerType
的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.