1

I think I miss something big about typescript, here is my current code:

import { EventEmitter } from "node:events";

interface IService extends EventEmitter {
  actions: string[];
  events?: string[];
}

// I know this is not some valid typescript here, but I just want to express the fact that
// createService expects a class type that inherits from EventEmitter AND 
// implements the IService interface
function createService<S extends IService>(ServiceClass: 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)

My issue is described in the comment above

TS playground

Guid
  • 2,137
  • 2
  • 20
  • 33
  • 2
    You are looking for a [construct signature](https://www.typescriptlang.org/docs/handbook/2/functions.html#construct-signatures) as shown [in this playground link](https://tsplay.dev/mL3E2N). This is almost certainly a duplicate, but if I can't find an appropriate question I might write up an answer here. – jcalz Mar 15 '23 at 16:03

0 Answers0