String cannot be used as object index

Why is TypeScript reporting an error when using the keyof type in the Utils.ts file?

export function escapeHtml(text: string) {
    const characters = {
        '&': '&',
        '"': '"',
        "'": ''',
        '<': '&lt;',
        '>': '&gt;'
    };

    return text.replace(/[<>&"']/g, function(x) {
        return characters[x];
    });
}

TypeScript is reporting the error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ '&': string; '"': string; "'": string; '<': string; '>': string; }'. No index signature with a parameter of type 'string' was found on type '{ '&': string; '"': string; "'": string; '<': string; '>': string; }'.ts(7053) when using the keyof type in the Utils.ts file. Why is this happening?

This error is occurring because TypeScript is unable to infer the correct type for the characters object when using the keyof type.

To fix this error, you can explicitly define the type of the characters object. Here’s the updated code:

export function escapeHtml(text: string) {
    const characters: Record<string, string> = {
        '&': '&amp;',
        '"': '&quot;',
        "'": '&#039;',
        '<': '&lt;',
        '>': '&gt;'
    };

    return text.replace(/[<>&"']/g, function(x) {
        return characters[x];
    });
}

By specifying Record<string, string> as the type for characters, you are telling TypeScript that characters is an object with string keys and string values. This allows TypeScript to correctly infer the type and eliminate the error.