0
votes

I have the following class and interface:

export class EnforceAjax implements Middleware {
  public handle(client: Client) {
    return client.ajax === true
  }
}

export interface Middleware {
  handle?(client: Client, ...args: any[]): boolean | Response
}

When I try to execute the following:

Router.group('/api', { middleware: [EnforceAjax] }, async () => require('./api'))


export interface RouterOptions {
  middleware?: (Middleware | string)[]
}

public static group(routePrefix: string, options: RouterOptions, callback: Function): void

I get the following error:

Type 'typeof EnforceAjax' is not assignable to type 'string | Middleware'. Value of type 'typeof EnforceAjax' has no properties in common with type 'Middleware'. Did you mean to call it?

The error goes away when I add the new keyword though however I don't want to pass an instance of the class as a value into the array.

1
Well, the static methods of EnforceAjax don't match the interface Middleware, only the instance methods do. So yeah, you'll want to pass an instance.p.s.w.g
The value EnforceAjax is not a Middleware, it's a constructor that produces a Middleware when newed. If you intend EnforceAjax to be a Middleware maybe you want handle() to be static?jcalz

1 Answers

1
votes

Then type middleware as a Middleware constructor:

 export interface RouterOptions {
   middleware?: ({ new(): Middleware; } | string)[]
 }

Not sure why you need a class at all though.