You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

引用JavaScript库时TypeScript无法调用构造函数求助

解决 crypto_1.SecretsStore is not a constructor 类型声明问题

这种报错几乎都是TypeScript类型声明和JavaScript实际导出结构不匹配导致的,结合你给出的代码来看,问题出在你的.d.ts声明和CommonJS风格的JS导出没对齐。

问题根源

你的JavaScript库用的是CommonJS导出:

module.exports = { SecretsStore }

但你的.d.ts用了ES模块风格的export class,TypeScript在解析时会对模块结构产生误解——运行时SecretsStore是挂载在模块导出对象上的属性,但TS的类型系统可能没有正确映射这个结构,导致运行时找不到构造函数。

修正后的类型声明文件

你可以直接调整.d.ts,让它完全匹配JS的导出结构,以下是两种可靠的写法:

写法1:保持ES模块风格导出(推荐)

export type Environment = 'local' | 'dev' | 'staging' | 'production';

export declare class SecretsStore {
  constructor(env: Environment, cacheFile?: string);
  isReady: () => boolean;
}

注意这里加了declare关键字(.d.ts里可以省略,但显式声明更清晰),同时确保类的成员都用分号结尾,符合TS语法规范。

写法2:适配CommonJS的export =语法

如果你的项目是纯CommonJS环境,也可以用这种写法:

export type Environment = 'local' | 'dev' | 'staging' | 'production';

declare class SecretsStore {
  constructor(env: Environment, cacheFile?: string);
  isReady: () => boolean;
}

export = { SecretsStore };

实用调试方法

如果以后再碰到类似的类型不匹配问题,可以试试这些技巧:

  • 打印运行时导出结构:在JS文件里加console.log(module.exports),或者在TS里导入模块后打印console.log(yourModule),对比实际导出和TS声明的差异。
  • 用typeof自动推导类型:写一个临时TS文件,导入JS模块后用typeof获取构造函数的真实类型,再把这个类型复制到.d.ts里。比如:
    // 临时测试文件
    import { SecretsStore } from './crypto';
    type SecretsStoreConstructor = typeof SecretsStore;
    
    然后把推导出来的类型转换成声明文件里的构造函数类型:
    export type SecretsStoreConstructor = {
      new(env: Environment, cacheFile?: string): {
        isReady: () => boolean;
      };
    };
    
  • 检查TS配置:确保tsconfig.json里的module设置和你的项目模块系统一致(比如CommonJS项目设为"module": "CommonJS",ES模块项目设为"ESNext"),同时确认.d.ts文件在include配置的范围内,TS能正确识别它。

内容的提问来源于stack exchange,提问作者user2740775

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:18:31