node.jstypescriptexpressnamed-routing

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'.


Solution

  • 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;
        }
      }
    }