Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expressjs: typescript: Argument of type 'typeof <express.Router>' is not assignable to parameter of type 'RequestHandlerParams'

I am using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped. I defined a router and would like to use it from a subpath as is stated in the official 4.x documentation (app.use('/calendar', router);), but I get following error

Error: /Users/matthias/Documents/private workspace/universal/src/server/server.ts (161,34): Argument of type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"' is not assignable to parameter of type 'RequestHandlerParams'.
  Type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"' is not assignable to type '(RequestHandler | ErrorRequestHandler)[]'.
    Property 'length' is missing in type 'typeof "/Users/matthias/Documents/private workspace/universal/src/server/routes/login.router"'.

This is the router I am using, ommiting the actual code...

const router : express.Router = express.Router();
let loginController = new LoginController();

router.post('/signin', function(req: express.Request, res: express.Response, next: express.NextFunction) {

  ...

  })(req, res, next);
});

...

export default router;

... and this is the shortened version of the call to it.

import * as loginRouter from './routes/login.router';

private app = express();
this.app.use('/api/v1/auth', loginRouter);

Am I doing something wrong or is this usecase just not properly defined in the typescript definition files?

Kind Regards

like image 244
ArdentZeal Avatar asked Jul 05 '17 08:07

ArdentZeal


3 Answers

Found it, import * as ... seems to lose its typescript information (IRouter, Router)

Solution is to use import loginRouter from './routes/login.router'; instead

like image 193
ArdentZeal Avatar answered Nov 12 '22 13:11

ArdentZeal


I fixed this issue by removing

export default router;

at the end of my router module. I simply exported it where I created it

export const router = express.Router();

and then updated any imports of the module accordingly.

I don't know why the compiler had trouble with the default export, but I know that TypeScript's default exports are not identical to ECMAScript's default exports.

like image 4
Seth Avatar answered Nov 12 '22 11:11

Seth


I was doing silly mistake and waited for a long time to check solution

I was using an app property as a method

app('/account', accountRoutes)

but I need to use use() method instead

app.use('/account', accountRoutes)
like image 1
WasiF Avatar answered Nov 12 '22 13:11

WasiF