![](/img/trans.png)
[英]No overload matches this call. The last overload gave the following error. Type '“text”' is not assignable to type '“json”'
[英]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
的定義方式是為鍵返回string
或undefined
。 一種處理方法是檢查並拋出這樣的錯誤:
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.