2

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

qqilihq
  • 10,794
  • 7
  • 48
  • 89
  • Could you share your `express-named-routes.d.ts` or submit it to DefinitelyTyped? – Forseti May 19 '18 at 17:04
  • 1
    @Forseti Yes, I will do. I'm currently on vacation until end of month, but I put myself a reminder. Thanks for your patience. – qqilihq May 19 '18 at 23:04
  • have a good vacation then :) I asked because for my the solution in answer isn't working and I wonder if I miss the bigger scope or something. I'm quite new to TypeScript so this is possible :) – Forseti May 20 '18 at 05:55
  • 1
    @Forseti Managed to finished the typings -- feel free to have a look at the PR on DefinitelyTyped: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26403 – qqilihq Jun 09 '18 at 11:10

2 Answers2

1

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

Update: I’ve made the typings now available on DefinitelyTyped via @types/named-routes.

qqilihq
  • 10,794
  • 7
  • 48
  • 89