繁体   English   中英

没有重载匹配这个调用。 最后一次重载在打字稿中出现以下错误

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

我写了关于使用文件 .env 加密传入函数 cryto 的字符串的代码,但出现错误行我不知道这意味着什么。 我在 .env 文件中使用环境配置值并导出默认值并在需要它们的情况下使用但错误行显示“没有重载匹配此调用。最后一个重载给出了以下错误。

    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; }"

像这样。

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);
  }
};

最有可能的是,您的environment的定义方式是为键返回stringundefined 一种处理方法是检查并抛出这样的错误:

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);
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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