Search code examples
angulartypescripttypes

Angular: Object key accessible via variable on component but not on HTML


I have some strings on an object that I export in the environment file so that I can use those values globally.

This is my environment.ts

export interface RegionNames {
  br: any;
  bo: any;
}

export const environment = {
  production: false,
  region_id: "br",
};

export const region_phrases: RegionNames = {
  br: {
    "string1": "A",
    "string2": "B",
    "string3": "C",
    "string4": "D",
    "string5": "E",
  },
  bo: {
    "string1": "AA",
    "string2": "BB",
    "string3": "CC",
    "string4": "DD",
    "string5": "EE",
  }
}

This is in the component script, where I can successfully gather the strings from the object:

console.log(region_phrases[environment.region_id as keyof RegionNames].string1);

But when I try to run the exact same code on the HTML template, it returns an error:

<span class="visually-hidden">{{ region_phrases[environment.region_id as keyof RegionNames].string1 }}</span>

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'RegionNames'. No index signature with a parameter of type 'string' was found on type 'RegionNames'.

<span class="visually-hidden">{{ region_phrases[environment.region_id as keyof RegionNames].string1 }}</span>

I don't want to create variables for the object in every component in my project just to access it in the HTML, is there a way to fix this more easily?


Solution

  • Specify the environment type as:

    export const environment: { production: false; region_id: keyof RegionNames } =
      {
        production: false,
        region_id: 'br',
      };
    

    In your HTML, remove as keyof RegionNames.

    <span class="visually-hidden">{{ region_phrases[environment.region_id].string1 }}</span>
    

    Demo @ StackBlitz