feathersjs / feathers

The API and real-time application framework
https://feathersjs.com
MIT License
15.02k stars 745 forks source link

Recommend way to type service class to use `this.emit()`? #3188

Closed nmccrea closed 1 year ago

nmccrea commented 1 year ago

In the documentation on custom events it shows the following example code for TypeScript:

class PaymentService {
  async create(data: any, params: Params) {
    const customer = await createStripeCustomer(params.user)
    this.emit('status', { status: 'created' })

    const payment = await createPayment(data)
    this.emit('status', { status: 'completed' })

    return payment
  }
}

But this will produce a TypeScript error at this.emit:

Property 'emit' does not exist on type 'PaymentService'.

I can solve this with PaymentService extends EventEmitter, but it seems like it would be better if there was a Feathers typing solution. I've been unsuccessful solving the issue using Feathers' types. For example, the FeathersService type includes the emit() addon but since it is only an interface, PaymentService implements FeathersService<...> doesn't actually endow the class with this property. Any recommendations on the best way to type this?