向基类添加方法声明

时间:2019-03-31 02:26:58

标签: typescript koa-router

我想向koa-router get方法中添加一个声明,该声明使我可以使用TypeORM实现路由模型绑定。

类似以下内容:

router.get("/photos/:photo", (photo: Photo) => {
  return { photo }
});

如果我要调用/photos/1,它将返回Photo对象为JSON。

koa-router的键入位于https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa-router/index.d.ts#L184

因此,我尝试了扩展类,声明基类方法参数以及添加其他声明。

import * as Router from 'koa-router'

export class LoopedRouter<StateT, CustomT> extends Router {

  get(path: string | RegExp | (string | RegExp)[], ...middleware: Array<Router.IMiddleware<StateT, CustomT>>): Router<StateT, CustomT>;

  get(path: string, callback: Function): Router {

    // code here to support base class and extended API

    let args = resolveModels(path, callback)

    return super.get(path, ctx => callback(...args))
  }
}

但是我从tsc收到以下错误:

error TS2416: Property 'get' in type 'LoopedRouter<StateT, CustomT>' is not assignable to the same property in base type 'Router<any, {}>'.
      Type '(path: string | RegExp | (string | RegExp)[], ...middleware: Middleware<ParameterizedContext<StateT, CustomT & IRouterParamContext<StateT, CustomT>>>[]) => Router<StateT, CustomT>' is not assignable to type '{ (name: string, path: string | RegExp, ...middleware: Middleware<ParameterizedContext<any, IRouterParamContext<any, {}>>>[]): Router<any, {}>; (path: string | RegExp | (string | RegExp)[], ...middleware: Middleware<...>[]): Router<...>; <T, U>(name: string, path: string | RegExp, middleware: Middleware<...>, routeH...'.
        Types of parameters 'middleware' and 'path' are incompatible.
          Type 'string | RegExp' is not assignable to type 'Middleware<ParameterizedContext<StateT, CustomT & IRouterParamContext<StateT, CustomT>>>'.
            Type 'string' is not assignable to type 'Middleware<ParameterizedContext<StateT, CustomT & IRouterParamContext<StateT, CustomT>>>'.

    5   get(path: string | RegExp | (string | RegExp)[], ...middleware: Array<Router.IMiddleware<StateT, CustomT>>): Router<StateT, CustomT>;

0 个答案:

没有答案