首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >属性“微妙”在类型“webcrypto”中不存在

属性“微妙”在类型“webcrypto”中不存在
EN

Stack Overflow用户
提问于 2022-03-18 10:15:10
回答 1查看 1.1K关注 0票数 7

我正在使用Nodev17.4,并且希望使用webcrypto。基于这个例子,我试图将subtle导入到我的项目中,但是TypeScript出现了错误

属性“微妙”不存在于类型“webcrypto”上。

webcrypto提供的唯一的名称空间是

代码语言:javascript
复制
import crypto from 'crypto';
const { subtle } = crypto.webcrypto; // subtle doesn't exist

如何访问subtle

EN

回答 1

Stack Overflow用户

发布于 2022-03-20 18:18:47

正如您已经注意到的,@types/node只包括webcrypto接口的存根。解决方法之一是扩展crypto模块声明,从DOM类型定义将webcrypto.subtle声明为SubtleCrypto

代码语言:javascript
复制
// src/types/index.d.ts

declare module "crypto" {
  namespace webcrypto {
    const subtle: SubtleCrypto;
  }
}

这允许编写如下模块:

代码语言:javascript
复制
// 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类型定义。例如,安装了以下软件包:

代码语言:javascript
复制
$ npm install -D typescript@4.6 @types/node@17 @tsconfig/node17

和一个tsconfig.json,包含:

代码语言:javascript
复制
{
  "extends": "@tsconfig/node17/tsconfig.json",
  "compilerOptions": {
    "lib": ["dom"],
    "outDir": "dist",
    "typeRoots": ["./node_modules/@types", "./src/types"]
  },
  "include": ["src/**/*"],
  "exclude": ["dist", "node_modules"]
}

您可以编写一个入口点,调用digest并打印结果:

代码语言:javascript
复制
// 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"));
})();

它构建并运行,如:

代码语言:javascript
复制
$ npx tsc && node dist/index.js
374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71525466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档