2

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?

6
  • 1
    I think you can extend interface to be able to index using string like; interface A { [b: string]: string } You can look over to this playground Commented Apr 29, 2020 at 5:49
  • Can you provide a reference? Commented Apr 29, 2020 at 5:57
  • check here; typescriptlang.org/docs/handbook/interfaces.html and search for index signatures Commented Apr 29, 2020 at 5:57
  • Does this answer your question? TypeScript Index Signature of object type implicitly has type any Commented Apr 29, 2020 at 5:59
  • 1
    Also, if you know _textValue will always be a key of Orientation you can use _textValue: keyof typeof Orientation. Commented Apr 29, 2020 at 6:00

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice. You can also write var params: IDictionary = {}; which is cleaner as no assertion is actually necessary here.
-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.