0

I want to add multiple keys to the dictionary via loop. For example, when I create a key, that key already has its value.

I have the following scenario:

var keys = ['key1', 'key2', 'key3', 'key4']
var dic = {}

for (let i = 0; i < keys.length; i++) {

    const key = keys[i]
    dic[key] = 'value' + i         
}

Note that I am adding several keys and already assigning the value of that key, but it does not work in TypeScript, so I have tested it works perfectly in JavaScript.

This line above has error. Note that I cannot add an element that is not contained in the array:

dic[key] = 'value' + i     

Error details

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

How can I get my Array keys and assign it to the dictionary with the loop value?

Isaac
  • 150
  • 1
  • 1
  • 12
  • 1
    *It does not work*: which code does not work? How does it not work? Post a minimal complete example which "does not work", tell what you're doing (compiling? running?) , tell what you expect to happen, and tell what happens instead. – JB Nizet Oct 15 '19 at 16:12
  • 1
    What type do you want `dic` to be? If you're okay with it being a dictionary of strings, then declare it as such (e.g., `var dic: { [k: string]: string } = {}`). Keep in mind that "it does not work" doesn't really count as a description of the problem as described in the guidelines for creating a [mcve]. Good luck! – jcalz Oct 15 '19 at 16:12
  • Got it, I made it clear now the line that gives the error in TypeScript – Isaac Oct 15 '19 at 16:18
  • jcalz, the code worked for me, I have to learn a lot yet – Isaac Oct 15 '19 at 16:24
  • excuse my question but why not working with object and set attributes as keys ? var Dic = { "one": "first", "two": 2} – MoxGeek Oct 15 '19 at 16:47
  • MoxGeek How can I do this? – Isaac Oct 15 '19 at 16:55

1 Answers1

0

You need to define the type of dic

  • Use any
var dic: any = {}
  • Be more precise
var dic: Record<string, string> = {}
  • Be even more precise
type Key = 'key1' | 'key2' | 'key3' | 'key4'
var keys: Key[] = ['key1', 'key2', 'key3', 'key4']
var dic: Partial<<Record<Key, string>> = {}
  • If the keys are static, then you can make it even better (credit to this thread)
const keys = ['key1', 'key2', 'key3', 'key4'] as const; // TS3.4 syntax
type Key = typeof keys[number];
var dic: Partial<Record<Key, string>> = {
  "key1": "123"
}
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77