I don't know how to fix the typescript error: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}'

I am a javascript developer and I am trying to write typescript. I understand the philosophy of typescript where you have to actually declare the types of variables. Instead of a function being doThis(param1) {..., you would write doThis(param1: string) {... I have this AWS lambda code that DOES work properly. The file is called app.ts and it looks like this:

import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';

/**
 *
 * Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
 * @param {Object} event - API Gateway Lambda Proxy Input Format
 *
 * Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
 * @returns {Object} object - API Gateway Lambda Proxy Output Format
 *
 */

export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
    let response: APIGatewayProxyResult;
    try {
        const words = JSON.parse(event.body).listedwords;
        let result = {}
        
        for (const word of words) {
            const sorted = word.split("").sort().join("");
        
            if (sorted in result) {
                result[sorted].push(word);
            } else {
                result[sorted] = [word];
            }
        }
        response = {
            statusCode: 200,
            body: result
        };
    } catch (err: unknown) {
        console.error(err);
        response = {
            statusCode: 500,
            body: JSON.stringify({
                message: err instanceof Error ? err.message : 'some error happened',
            }),
        };
    }

    return response;
};

The problem is on the lines result[sorted].push(word); and result[sorted] = [word];, I get the typescript error "Element implicitly has an ‘any’ type because expression of type ‘any’ can’t be used to index type ‘{}’." in vscode.
enter image description here

How could I modify the code to be acceptable for typescript? Again the code works… I just want to know how to fix this error to improve my typescript.

>Solution :

The reason you’re getting that error is because sorted could be any type of value (number, object, undefined, etc) and object’s keys need to be of type string.

Indicate that the type for the result variable is an object with keys of type string and values of type string[]

let result: Record<string, string[]> = {}

Now you should be able to access the key for the result variable and push words to that array

for (const word of words) {
    const sorted = word.split("").sort().join("");
    if (sorted in result) {
        result[sorted].push(word);
    } else {
        result[sorted] = [word];
    }
}

Leave a Reply