Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Typescript definitions to Express req & res

I have a set of controller functions for my REST API and I'm getting lots of the following

error TS7006: Parameter 'req' implicitly has an 'any' type. 

Likewise for res. I've been playing around with typeings etc. but with no success. For example the Request type parameter below does NOT work.

Here is an example of the controller files. The reference path is correct.

/// <reference path="../../../typings/tsd.d.ts" />     /* globals require */     "use strict";     exports.test = (req : Request, res) => { 

I tried adding import * as express from "express"; into the file - I don't need it normally as these functions are exported and use by index.js which actually implements the routing.

And this is tsd.d.ts

/// <reference path="requirejs/require.d.ts" /> /// <reference path="express/express.d.ts" /> /// <reference path="mime/mime.d.ts" /> /// <reference path="node/node.d.ts" /> /// <reference path="serve-static/serve-static.d.ts" /> /// <reference path="bluebird/bluebird.d.ts" /> /// <reference path="mongoose/mongoose.d.ts" /> 
like image 959
Simon H Avatar asked Dec 29 '15 09:12

Simon H


People also ask

Can you use TypeScript with Nodejs?

TypeScript is well-established in the Node. js world and used by many companies, open-source projects, tools and frameworks. Some of the notable examples of open-source projects using TypeScript are: NestJS - robust and fully-featured framework that makes creating scalable and well-architected systems easy and pleasant.

Can Express be written in TypeScript?

With TypeScript configured, we can create the Express web server. First, create the file index. ts (attention to the file extension) by running touch index.


1 Answers

You can use ES6 style named imports to import only the interfaces you need, rather than import * as express from 'express' which would include express itself.

First, make sure you have installed the type definitions for express (npm install -D @types/express).

Example:

// middleware/authCheck.ts import { Request, Response, NextFunction } from 'express';  export const authCheckMiddleware = (req: Request, res: Response, next: NextFunction) => {   ... };  // server.ts import { authCheckMiddleware } from './middleware/authCheck'; app.use('/api', authCheckMiddleware); 

Currently using TypeScript 2.3.4 and @types/express 4.0.36.

like image 137
J. NZ Avatar answered Oct 06 '22 23:10

J. NZ