'Typescript issue referencing item in the object via variable

I am rewriting nodejs application into typescript and I am facing an issue I am unable to resolve. I get a cryptic message: 'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type' (7053).

Here is an example of my code:

function translationFunction(type: string, section: string, language: string) {

  let translations = {
    type1: {
      section1: {
        en: 'I mean this',
        es: 'quiero decir esto'
      },
      section2: {
        en: 'I do not understand',
        es: 'no entiendo'
      },
    },
    type2: {
      section1: {
        en: 'I mean this',
        es: 'quiero decir esto'
      },
      section2: {
        en: 'I do not understand',
        es: 'no entiendo'
      },
    }
  }


    //return console.log(translations.type1.section2.en); - this works
    return translations[type][section][language] // this does not work in typescript but works in javascript

}


translationFunction('type1', 'section2', 'es');

I am looking for a solution and I understand this needs to be treated with an interface?

  interface translationsInterface {
      [key: string]: any,
  }

  let translations: translationsInterface = {};

I have tried for something that would resolve this issue but that does not work for me. I am still getting errors.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source