Home > Net >  TypeScript - How to access dictionary value by key?
TypeScript - How to access dictionary value by key?

Time:03-18

I have a dictionary of dictionaries which looks like this:

options: { language: string; value: { parameterId: string; parameterValue: string } }[];

When I inspect an instance of this at runtime, it looks like this:

{de: Object, en: Object}
de:{1: "-", 2: "grün", 3: "gelb", 4: "rot" }
en:{1: "-", 2: "green", 3: "yellow", 4: "red" }
__proto__:{}

I am now trying to write a function which returns one of those dictionaries depending on these rules:

  1. If there is an entry with key "-", return this entry.
  2. Else if there is an entry with the current browser language as key, return it.
  3. Else if there is an entry with key "en", return it.
  4. Else return an empty dictionary.

This is my first attempt to write this function:

filterOptions(
  options: { language: string; value: { parameterId: string; parameterValue: string } }[],
) {
  const languageIndependentKey = "-";

  if (languageIndependentKey in options) {
    return options[languageIndependentKey];
  }
  if (this.translate.currentLang in options) {
    ...
  } else if ("en" in options) {
    ...
  } else {
    ...
  }
}

This does not seem to work because I get the following error in the line return options[languageIndependentKey];:

error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.

I simply cannot figure out how to write this function without causing this error. How can I check if a specific key is present in the dictionary and return the corresponding dictionary at that key? I can't imagine that this is so difficult, but everything I tried so far did not work.

For some reason, this code runs just fine:

for (const language in options) {
  return options[language];
}

But directly accessing an entry like options["en"] causes an error. Why? Is my declaration of the dictionary type incorrect, or what is going on here?

CodePudding user response:

You may try the following interface. Swap it with your code, in case everything else is structured properly.

{
 language: string,      
 [key: string]: {
 parameter
  .....
}

Also you have wrong type next to parameter, it should be number from what I see.

CodePudding user response:

I was able to fix the problem myself by using the type ParameterOptions which is defined as follows:

export class ParameterOptions {
  [language: string]: { [parameterId: number]: string };
}
  • Related