Angular: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

3 days ago 2
ARTICLE AD BOX

I know there are plenty of post asking support for this error, but I wasn't able to find one that is close to my situation.

I'm migrating an old application from angular 6.1.10 and typescript 2.9.2 to angular 17.0.0 and typescript 5.2.2.
The application handle the translation between two languages using this code declared in the index.ts of the folder where are defined the labels and their translations:

import { EN } from './en'; import { IT } from './it'; export const MESSAGES = { en: EN, it: IT }; export type Lang = 'en' | 'it'; export type MessageKey = keyof typeof EN;

inside the I18nService there is a method where given a key it return its tranlsation:

get(key: string, params?: any): string { let text = (MESSAGES[this.lang] && MESSAGES[this.lang][key]) || (MESSAGES['en'] && MESSAGES['en'][key]) || key; if (params) { Object.keys(params).forEach(p => { text = text.replace(`{{${p}}}`, params[p]); }); } return text; }

the error is on the line where text is declared: accessing the matrix MESSAGES using as second index "key" is no more allowed.

I tried to use "key as keyof typeof MESSAGES" but it's not correct. Which is the correct syntax?

Stefania's user avatar

2

Read Entire Article