webber
webber

Reputation: 765

How to dynamically get the value of an object with a key that is stored in a variable

I have an object in Typescript, I am trying to dynamically change the string of the key. The below isn't working as expected. It throws the following Typescript error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

'{ key1: string; key2: string; }'.

No index signature with a parameter of type 'string' was found on type

'{ key1: string; key2: string; }'.ts(7053)
let c:string='key2'
var o = { key1: 'value1', key2: 'value2' };
var val = o[c]; //should return 'value2'

And if I change the variable c to 'key1', it should return 'value1'.

Thanks in advance. :)

Upvotes: 0

Views: 56

Answers (2)

Jack jdeoel
Jack jdeoel

Reputation: 4584

If you want to change dynamically key , you should create dynamic interface like below [key: string] is for dynamic key

<-------
interface Example {
   [key: string]: string
}
------->

var o: Example = { key1: 'value1', key2: 'value2' };
var val = o[c];

Upvotes: 0

iamhuynq
iamhuynq

Reputation: 5529

Maybe this helps

var o = { key1: 'value1', key2: 'value2' };
let c: keyof typeof o = 'key2'
var val = o[c];

Upvotes: 1

Related Questions