![](/img/trans.png)
[英]Property 'transformArticles' does not exist on type 'typeof Article'
[英]Property 'subtle' does not exist on type 'typeof webcrypto'
如您所述, @types/node
僅包含webcrypto
接口的存根。 一種解決方法是擴展crypto
模塊聲明以將webcrypto.subtle
聲明為來自 DOM 類型定義的SubtleCrypto
:
// src/types/index.d.ts
declare module "crypto" {
namespace webcrypto {
const subtle: SubtleCrypto;
}
}
這允許編寫如下模塊:
// src/digest.ts:
import * as crypto from "crypto";
// subtle has type SubtleCrypto, from the DOM type definitions
const { subtle } = crypto.webcrypto;
// Generate a cryptographic digest of the given message
export async function digest(message?: string, algorithm = "SHA-512") {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await subtle.digest(algorithm, data);
return hash;
}
要使用SubtleCrypto
,項目必須通過將dom
添加到tsconfig.json
中的lib
數組來啟用 DOM 類型定義。 例如,安裝了以下軟件包:
$ npm install -D typescript@4.6 @types/node@17 @tsconfig/node17
和一個tsconfig.json
包含:
{
"extends": "@tsconfig/node17/tsconfig.json",
"compilerOptions": {
"lib": ["dom"],
"outDir": "dist",
"typeRoots": ["./node_modules/@types", "./src/types"]
},
"include": ["src/**/*"],
"exclude": ["dist", "node_modules"]
}
您可以編寫一個調用digest
並打印結果的入口點:
// src/index.ts
import { digest } from "./digest";
const message = "Hello, World!";
(async () => {
const digestBuffer = await digest(message);
console.log(Buffer.from(new Uint8Array(digestBuffer)).toString("hex"));
})();
這構建並運行,如:
$ npx tsc && node dist/index.js
374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.