TypeScript泛型类与实现类型问题:createService类型定义报错
TypeScript泛型类类型参数修正方案
你当前的createService函数泛型约束逻辑有误——S extends IService约束的是实例类型,但函数参数ServiceClass是类(构造函数),二者类型不兼容,导致TS报错。
修正后的代码
import { EventEmitter } from "node:events"; interface IService { actions: string[]; events?: string[]; } // 泛型S约束为同时满足IService和EventEmitter实例的类型,参数是返回S实例的无参构造函数 function createService<S extends IService & EventEmitter>(ServiceClass: new () => S) { const s = new ServiceClass(); console.log(s.actions); console.log(s.events); return s; } class MyService extends EventEmitter implements IService { actions = ["action1", "action2"]; events = ["event1", "event2"]; action1(str: string) { this.emit("event1"); } action2(num: number) { return num; } } const service = createService(MyService);
关键说明
new () => S是TypeScript的构造函数类型,表示可通过new调用、返回S类型实例的类/构造函数。S extends IService & EventEmitter确保实例同时具备IService定义的属性,以及EventEmitter的实例方法(如emit、on)。- 调用
createService(MyService)时,TS会自动推导S为MyService类型,返回的service会保留原类的所有方法和属性类型。
内容的提问来源于stack exchange,提问作者Guid
相关产品推荐
相关产品推荐

