![](/img/trans.png)
[英]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.