TypeScript Node.js中TypeError: exports.Something不是构造函数问题求助
问题原因
你当前的代码只定义了TypeScript类型声明,没有提供Something的实际运行时实现。declare var Something: SomethingConstructor;仅用于告诉TypeScript这个变量的类型信息,编译为JavaScript后不会生成任何可执行代码,所以Node.js运行时找不到对应的构造函数,才会抛出TypeError: exports.Something is not a constructor。
正确实现方式
你需要写出符合SomethingConstructor接口的实际运行时逻辑,以下提供两种可行方案:
方案1:直接用函数实现(同时支持new和直接调用)
修改dummy.ts为以下代码:
interface Something { name: string; message: string; stack?: string; } interface SomethingConstructor { new(message?: string): Something; (message?: string): Something; readonly prototype: Something; } // 实现构造函数逻辑 const Something: SomethingConstructor = function(message?: string): Something { // 处理直接调用的情况(如Something("msg")) if (!(this instanceof Something)) { return new Something(message); } // 初始化实例属性 this.name = "Something"; this.message = message ?? "Default message"; // 可选:捕获调用栈 if (Error.captureStackTrace) { Error.captureStackTrace(this, Something); } } as SomethingConstructor; // 给原型挂载属性(按需添加) Something.prototype = { get name() { return "Something"; }, get message() { return this._message; } }; export { Something };
方案2:用类实现+包装函数(兼顾类的便捷性)
如果更习惯用类编写逻辑,可以先定义类,再包装成支持直接调用的函数:
interface Something { name: string; message: string; stack?: string; } // 核心逻辑用类实现 class SomethingImpl implements Something { name: string; message: string; stack?: string; constructor(message?: string) { this.name = "Something"; this.message = message ?? "Default message"; if (Error.captureStackTrace) { Error.captureStackTrace(this, SomethingImpl); } } } // 包装成同时支持new和直接调用的函数 const Something = Object.assign( function(message?: string) { return new SomethingImpl(message); }, { prototype: SomethingImpl.prototype, // 让instanceof判断正常工作 [Symbol.hasInstance](instance: any) { return instance instanceof SomethingImpl; } } ) as typeof SomethingImpl & ((message?: string) => Something); export { Something };
验证效果
你的原有使用代码无需修改,运行后会正常打印Here is a message,同时也支持直接调用const something = Something("直接调用的消息");。
注意:TypeScript的接口、类型声明仅用于编译时类型校验,不会生成运行时代码。如果需要运行时可用的构造函数/对象,必须编写具体的实现逻辑,不能仅依赖
declare声明类型。
内容的提问来源于stack exchange,提问作者Muhammad Haroon
相关产品推荐
相关产品推荐

