node-jsonwebtoken x TypeScriptで「No overload matches this call」エラー

npmの auth0/node-jsonwebtoken モジュールを使って、TypeScriptでJWT実装したときに発生したエラー。

現象

jwt.signのoptionsを指定すると以下のエラーが発生。

const options: {
    algorithm: string | undefined;
    issuer: string | undefined;
    audience: string | undefined;
    subject: string;
    jwtid: string;
    expiresIn: string | undefined;
}
No overload matches this call.

  Overload 1 of 3, '(payload: string | object | Buffer, secretOrPrivateKey: Secret, options?: SignOptions | undefined): string', gave the following error.
    Argument of type '{ algorithm: string | undefined; issuer: string | undefined; audience: string | undefined; subject: string; jwtid: string; expiresIn: string | undefined; }' is not assignable to parameter of type 'SignOptions'.
      Types of property 'algorithm' are incompatible.
        Type 'string | undefined' is not assignable to type 'Algorithm | undefined'.
          Type 'string' is not assignable to type 'Algorithm | undefined'.

  Overload 2 of 3, '(payload: string | object | Buffer, secretOrPrivateKey: Secret, callback: SignCallback): void', gave the following error.
    Argument of type '{ algorithm: string | undefined; issuer: string | undefined; audience: string | undefined; subject: string; jwtid: string; expiresIn: string | undefined; }' is not assignable to parameter of type 'SignCallback'.
      Type '{ algorithm: string | undefined; issuer: string | undefined; audience: string | undefined; subject: string; jwtid: string; expiresIn: string | undefined; }' provides no match for the signature '(error: Error | null, encoded: string | undefined): void'.ts(2769)

auth.ts(抜粋)

import jwt from 'jsonwebtoken';

    // Validation
    const jwtSecret = process.env.JWT_SECRET;
    if (!jwtSecret) throw new Error('JWT_SECRET not found.');

    const userAddress = 'HXtBm8XZbxaTt41uqaKhwUAa6Z1aPyvJdsZVENiWsetg';

    // Create JWT
    const payload = {
      address: userAddress,
    };

    const options = {
      algorithm: process.env.JWT_ALGORITHM,
      issuer: process.env.JWT_ISSUER, // Issuer mail address
      audience: process.env.JWT_AUDIENCE, // Web domain
      subject: userAddress, // User unique ID
      jwtid: uuidv4(), // Token random unique ID
      expiresIn: process.env.JWT_EXPIRES_IN,
    };

    const token = jwt.sign(payload, jwtSecret, options);

原因

optionsのalgorithmに型指定がないため。

      algorithm: process.env.JWT_ALGORITHM,

対応

Algorithm をインポートしてからasで型指定する。

import jwt, { Algorithm } from 'jsonwebtoken';

      algorithm: process.env.JWT_ALGORITHM as Algorithm,