Typescript is throwing an error with crypto generateKeyPair 'rsa'

Viewed 712

I have a function where I am attempting to generate public and private PEM key strings where I will use the private to generate a signed JWT token and store the public key in a database.

The NodeJS version is working in several production apps, but when adding this to one of the typescript projects, we are getting a mystery error.

// javascript version
const newCrypto = () => {
  return new Promise((resolve, reject) => {
    try {
      crypto.generateKeyPair('rsa', {
        modulusLength: 1024,
        publicKeyEncoding: {
          type: 'spki',
          format: 'pem'
        },
        privateKeyEncoding: {
          type: 'pkcs8',
          format: 'pem'
        }
      }, (err, publicKey, privateKey) => {
        if (err) throw err
        resolve({ publicKey, privateKey })
      })
    } catch (err) {
      reject(err)
    }
  })
}
// typescript version
const newCrypto = async (): Promise<any> => {
  crypto.generateKeyPair('rsa', {
    modulusLength: 1024,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem'
    }
  }, (err: Error, publicKey: string, privateKey: string) => {
    if (err) throw err
    return { publicKey, privateKey }
  })
}

This is the following error that I am getting from Typescript. After spending some time googling, I found nothing online regarding this issue. Anyone have any ideas?

No overload matches this call.
  The last overload gave the following error.
    Argument of type '"rsa"' is not assignable to parameter of type '"x448"'.

8   crypto.generateKeyPair('rsa', {
1 Answers

After looking through the crypto.d.ts file, I saw that the callback function could potentially return null in place of the error.

Below is the type definition:

function generateKeyPair(
        type: 'rsa',
        options: RSAKeyPairOptions<'pem', 'pem'>,
        callback: (err: Error | null, publicKey: string, privateKey: string) => void,
    ): void;

Solution:

const newCrypto = async (): Promise<any> => {
  crypto.generateKeyPair('rsa', {
    modulusLength: 1024,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem'
    }
  }, (err: Error | null, publicKey: string, privateKey: string) => {
    if (err) throw err
    return { publicKey, privateKey }
  })
}

By adding a null callback error type, the error was resolved.

Related