我有一个对象,我想使用字符串索引访问对象值,但是当我尝试在 TypeScript 中执行此操作时,出现错误。
// Declared Globally
const Orientation = {
value: () => 0,
'next_value': () => someFunction.anotherFunction.sqrt(),
};
// _textValue type declared
_textValue : string;
// Declared inside constructor
this._textValue = 'next_value';
// value used inside a function
_getValue(){
const newValue = Orientation[this._textValue]();
}
在我使用的地方Orientation[this._textValue]();
,我收到的错误是:
元素隐式具有 'any' 类型,因为类型 'any' 的表达式不能用于索引类型 '{ value: () => number; 'next_value': () => 数字;}'.ts(7053)
关于如何解决这个问题的任何想法?
主文件
export {}
interface IDictionary {
[index: string]: string;
}
var params = {} as IDictionary;
//array with string index
params = {a: "Bhavesh",b: "Bond", c: "Urmil"};
//get array data using string index
var getData = params['b']; // output: Bond
var getData = params['B']; // output: undefined
console.log(getData);
我认为您的问题将在上面的示例代码中得到解决。谢谢..!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句