In JsDoc should `[key: string]: any;` allow me to use any key value property?

Viewed 79

I am using npm pacakge jsonwebtoken, and the jwt.verify method. When I try to deconstruct the return value I get a intellisense error

Property 'userId' does not exist on type 'string | JwtPayload'.

My code looks like this.

({ userId } = jwt.verify(token, 'my_secret'));

When I look at the index.d.ts for jsonwebtoken it has this

export function verify(token: string, ...): JwtPayload | string;
export interface JwtPayload {
    [key: string]: any;
    iss?: string | undefined;
    ...
}

Shouldn't the [key: string]: any; allow me to create any key value property?

Why do i still get type errors and is there a way to get rid of them using jsdocs?

2 Answers

If you use brackets to access the value then it will not complain.

Something like this

const payload = jwt.verify(token, 'my_secret'))

payload["userId"];

Use a typeof type guard to check if the result is of type object:

let userId;
const jwtPayload = jwt.verify(token, 'my_secret');
if (typeof jwtPayload === 'object') {
    ({ userId } = jwtPayload);
}

Or force the type to be JwtPayload by casting it:

({ userId } = /** @type {jwt.JwtPayload} */(jwt.verify(token, 'my_secret')));
Related