如何在搭配@types/jsbn的TypeScript项目中访问SecureRandom?
问题核心原因
@types/jsbn@1.2.29版本的类型定义存在导出缺漏:原jsbn运行时模块本身是完整暴露SecureRandom类的,但配套类型声明只定义了BigInteger类、RandomGenerator抽象接口,没有把SecureRandom作为可导出的类写入类型规则,才导致TS场景下提示可用导出极少、导入报错。
可行解决方案
方案1:补丁补全缺失类型(长期维护推荐)
这是最贴合原有JS使用逻辑、不侵入业务代码的方案:
- 在项目全局类型目录(通常为
src/types/)下新建jsbn-shim.d.ts文件,补充缺失的类型声明:
declare module 'jsbn' { export class SecureRandom { constructor(); nextBytes(arr: Uint8Array | number[]): void; } }
- 补全类型后即可直接使用标准具名导入,和JS阶段的使用逻辑完全对齐:
import { SecureRandom, BigInteger } from 'jsbn'; // 实际调用逻辑和原JS写法完全一致 const secureRandom = new SecureRandom(); const x = new Uint8Array(16); secureRandom.nextBytes(x);
方案2:临时绕开类型校验(快速调试使用)
如果不需要长期维护类型准确性,可直接利用模块默认导入的运行时能力,通过类型断言绕开缺失的类型提示:
import jsbn from 'jsbn'; // 从运行时模块对象上取真实存在的SecureRandom构造函数 const SecureRandom = jsbn.SecureRandom as new () => { nextBytes(arr: Uint8Array | number[]): void }; const secureRandom = new SecureRandom();
常见错误提醒
- 不要使用
RandomGenerator as SecureRandom的别名导入写法:RandomGenerator在@types/jsbn中只是不可实例化的抽象接口,这么写运行时根本拿不到对应的构造函数,会触发SecureRandom is not a constructor的运行时报错。 - 不需要修改jsbn本身的源码、也不需要降级jsbn版本,原jsbn模块的运行时导出逻辑完全符合你原来的JS使用习惯,所有问题都来自配套类型定义的缺漏。
内容的提问来源于stack exchange,提问作者Sithideth Bouasavanh
相关产品推荐
相关产品推荐

