简体   繁体   中英

No overload matches this call. The last overload gave the following error in typescript

i wrote the code about encrypt the string that pass in function cryto with file .env but the appear the error line i don't know what that means. i config values in .env file with environment and export default them and use in the case need them but error line show "No overload matches this call. The last overload gave the following error.

    Argument of type 'string | undefined' is not assignable to parameter of type 'WithImplicitCoercion<string> | { [Symbol.toPrimitive](hint: "string"): string; }'.
      Type 'undefined' is not assignable to type 'WithImplicitCoercion<string> | { [Symbol.toPrimitive](hint: "string"): string; }"

like this.

import { randomBytes, createCipheriv, createDecipheriv } from "crypto";
import environment from "../environment";
const ENCRYPTION_KEY = environment.encrypt_Key;
// const enc = "klyH2NOdPmmFPtdCAHIIGgjMowUUd69P";
const IV_LENGTH = 16;

export const encrypt = async (text: string) => {
  try {
    let iv = randomBytes(IV_LENGTH);
    let cipher = createCipheriv("aes-256-cbc", Buffer.from(ENCRYPTION_KEY), iv);
    let encrypted = Buffer.concat([cipher.update(text), cipher.final()]);

    return `${iv.toString("hex")}:${encrypted.toString("hex")}`;
  } catch (e) {
    console.error(e);
  }
};

Most likely, your environment is defined in such a way that it either returns string or undefined for a key. One way to handle is to check that and throw error like this:

export const encrypt = async (text: string) => {
  // check if ENCRYPTION_KEY is set
  if(!ENCRYPTION_KEY) {
     throw new Error("encrypt_Key is not set");
  }

  try {
    let iv = randomBytes(IV_LENGTH);
    let cipher = createCipheriv("aes-256-cbc", Buffer.from(ENCRYPTION_KEY), iv);
    let encrypted = Buffer.concat([cipher.update(text), cipher.final()]);

    return `${iv.toString("hex")}:${encrypted.toString("hex")}`;
  } catch (e) {
    console.error(e);
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM