qqilihq
qqilihq

Reputation: 11474

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

Upvotes: 2

Views: 1705

Answers (2)

qqilihq
qqilihq

Reputation: 11474

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

Upvotes: 1

Timo van Kessel
Timo van Kessel

Reputation: 26

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

Upvotes: 1

Related Questions