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?

Arjun V
  • 197
  • 4
  • 16
  • 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](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgCrIN4Chm+QbTgC5kBnMKUAcwF0TzKQqsBfLLBAexHOQRPQBeTDjwAiOGJJiAFhAA28zmIA0o3ACNpkcqvV9pcDQjGt2XHp3kQAdEqoAKBPgliaASgDcHbqSu37JxcNNy8fS2s7TkcEGwQvIA) – Dipesh Dulal Apr 29 '20 at 05:49
  • Can you provide a reference? – Arjun V Apr 29 '20 at 05:57
  • check here; https://www.typescriptlang.org/docs/handbook/interfaces.html and search for index signatures – Dipesh Dulal Apr 29 '20 at 05:57
  • Does this answer your question? [TypeScript Index Signature of object type implicitly has type any](https://stackoverflow.com/questions/33350313/typescript-index-signature-of-object-type-implicitly-has-type-any) – Lauren Yim Apr 29 '20 at 05:59
  • 1
    Also, if you know `_textValue` will always be a key of `Orientation` you can use `_textValue: keyof typeof Orientation`. – Lauren Yim Apr 29 '20 at 06:00
  • What about the interface for the arrow function? – Arjun V Apr 29 '20 at 06:19

1 Answers1

8

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

Bhavesh Ajani
  • 991
  • 9
  • 11