【发布时间】: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