如何使用字符串索引访问 TypeScript 中的对象值

Arj*_*n V 2 javascript typescript

我有一个对象,我想使用字符串索引访问该对象值,但是当我尝试在 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]();
 }
Run Code Online (Sandbox Code Playgroud)

在我使用的地方Orientation[this._textValue]();,我收到的错误如下:

元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引类型“{ value: () => number;” '下一个值': () => 数字; }'.ts(7053)

关于如何解决这个问题有什么想法吗?

小智 11

主要.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);
Run Code Online (Sandbox Code Playgroud)

我认为您的问题将在上面的示例代码中得到解决。谢谢..!