简体   繁体   中英

Extend Express JS router TypeScript definition for “named-routes”

We're using an extension called named-routes with Express which has served us quite well in the past. Now that we're gradually TypeScript-ifying our codebase, we are facing following issue: The module extends Express' router object, so that routes can have an identifier:

router.get('/admin/user/:id', 'admin.user.edit', (req, res, next) => …

The Express typings are of course not aware of the this optional identifier and report a compile error. I followed the instructions from “Module Augmentation” and created the following express-named-routes.d.ts :

import { IRouterMatcher } from 'express';
import { PathParams, RequestHandlerParams } from 'express-serve-static-core';

declare module 'express' {
  export interface IRouterMatcher<T> {
    // copied from existing decl. and added the `name` argument
    (path: PathParams, name: string, ...handlers: RequestHandler[]): T;
    (path: PathParams, name: string, ...handlers: RequestHandlerParams[]): T;
  }
}

And of course imported it in the corresponding file:

 import '../types/express-named-routes'

But this still gives me an error TS2345: Argument of type '"my.route.name"' is not assignable to parameter of type 'RequestHandlerParams'.

Try wrapping it inside a module called 'named-routes' like this:

declare module 'named-routes' {
  import { IRouterMatcher } from 'express';
  import { PathParams, RequestHandler, RequestHandlerParams } from 'express-serve-static-core';

  module 'express-serve-static-core' {
    export interface IRouterMatcher<T> {
    // copied from existing decl. and added the `name` argument
      (path: PathParams, name: string, ...handlers: RequestHandler[]): T;
      (path: PathParams, name: string, ...handlers: RequestHandlerParams[]): T;
    }
  }
}

更新:我已经通过@types/named-routes提供了现在在确定@types/named-routes上可用的@types/named-routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM