Reputation: 197
I have an object and I want to access the object value using a string index, but when I try to do that in TypeScript, I'm getting errors.
// 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]();
}
And where I use Orientation[this._textValue]();
, I'm getting the error as:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ value: () => number; 'next_value': () => number; }'.ts(7053)
Any idea on how to resolve this?
Upvotes: 2
Views: 5728
Reputation: 616
This is the first link google shows me for this problem. The easiest way i found is converting the object to any first:
const newValue = (Orientation as any)[this._textValue]();
And that's pretty much it.
Upvotes: -1
Reputation: 1261
main.ts
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);
I think your problem will be solved in the above example code. thank you..!
Upvotes: 11