Search code examples
javascripttypescripttypescript-typingsdynamic-typing

How to type in one line an javascript object in Typescript, were a root property has a variable name


I have the following javascript object:

var termsAndConditions = {
    pt: ["url1", "url2"],
    en: ["url3", "url4"]
}

And I want to type it in Typescript in just one line. Something like this:

const termsAndConditions: {[countryKey: Array<string>]} = {
    pt: ["url1", "url2"],
    en: ["url3", "url4"]
}

And then use it like this:

const ptUrls: Array<string> = termsAndConditions.pt;
const enUrls: Array<string> = termsAndConditions.en;

How can I accomplish that?


Solution

  • You can do this:

    const termsAndConditions: { [countryKey: string]: string[] } = {
        pt: ["url1", "url2"],
        en: ["url3", "url4"]
    }
    

    Later you do not need to add the extra typing, as it is already specified

    Eg.

    const ptUrls = termsAndCondition.pt