簡體   English   中英

“typeof webcrypto”類型上不存在屬性“subtle”

[英]Property 'subtle' does not exist on type 'typeof webcrypto'

我正在使用 Node v17.4 並希望使用 webcrypto API。基於此示例,我嘗試將subtle導入到我的項目中,但 TypeScript 出現錯誤

“typeof webcrypto”類型上不存在屬性“subtle”。

命名空間webcrypto提供的是這個

import crypto from 'crypto';
const { subtle } = crypto.webcrypto; // subtle doesn't exist

我如何獲得subtle

如您所述, @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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM