sewb
sewb

Reputation: 147

Element implicitly has an 'any' type because index expression is not of type 'number'. - Index Signature error

I am new to TypeScript and I am getting

Element implicitly has an 'any' type because index expression is not of type 'number'

on this line --> const { status, msg } = codes[err.code];

I am not too sure how to fix it.

Here is the code:

    export const handlePSQLErrors = (
    err: { status: number; msg: string; code: string | number },
    req: Request,
    res: Response,
    next: NextFunction
) => {
    const codes: any = {
        '22P02': { status: 400, msg: 'Bad Request' },
        42703: { status: 400, msg: 'Bad Request' },
        23502: { status: 400, msg: 'Bad Request' },
        23503: { status: 404, msg: 'Bad Request' },
    };

    function hasKey<O>(obj: O, key: keyof any): key is keyof O {
        return key in obj;
    }

    if (hasKey(err.code, codes)) {
        const { status, msg } = codes[err.code];

        res.status(status).send({ msg });
    } else next(err);
};

Help to explain what is going on and how to fix it would be much appreciated.

Thanks

Upvotes: 1

Views: 96

Answers (1)

Julian
Julian

Reputation: 36710

There is not an typing issue, but there is a wrong call.

You get this error on the line:

const { status, msg } = codes[err.code];

But there real error is this:

if (hasKey(err.code, codes)) {

should be (swap the arguments)

if (hasKey(codes, err.code)) {

As hasKey is defined that the key is send as 2nd argument

Upvotes: 1

Related Questions