【问题标题】:typeof EnforceAjax is not assignable to type Middlewaretypeof EnforceAjax 不可分配给类型中间件
【发布时间】:2019-08-16 01:05:43
【问题描述】:

我有以下类和接口:

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

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

当我尝试执行以下操作时:

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


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

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

我收到以下错误:

类型 'typeof EnforceAjax' 不可分配给类型 'string |中间件”。 “typeof EnforceAjax”类型的值与“Middleware”类型没有共同的属性。你的意思是给它打电话吗?

当我添加 new 关键字时,错误消失了,但是我不想将类的实例作为值传递到数组中。

【问题讨论】:

  • 嗯,EnforceAjax 的静态方法不匹配接口Middleware,只有 instance 方法匹配。所以是的,你需要传递一个实例。
  • EnforceAjax 不是Middleware,它是一个构造函数,当newed 时产生Middleware。如果你想让EnforceAjax 成为Middleware,也许你想让handle() 成为static

标签: javascript typescript


【解决方案1】:

然后键入middleware 作为中间件构造函数:

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

不知道为什么你需要一门课。

【讨论】:

  • 我正在使用一个类,因为一些中间件类可能更复杂一些。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 2021-10-29
  • 1970-01-01
  • 2021-05-15
  • 2016-11-21
相关资源
最近更新 更多