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]();
}
และเมื่อฉันใช้ Orientation[this._textValue](); ฉันได้รับข้อผิดพลาดดังนี้:
องค์ประกอบมีประเภท 'any' โดยอัตโนมัติเนื่องจากนิพจน์ของประเภท 'any' ไม่สามารถใช้เพื่อเป็นดัชนีของประเภท '{ value:() => number; 'next_value':() => number; }'.ts(7053)
มีไอเดียเกี่ยวกับวิธีแก้ปัญหานี้ไหม?
คำตอบ #1
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);ผมคิดว่าปัญหาของคุณจะถูกแก้ไขในโค้ดตัวอย่างด้านบน ขอบคุณ..!
