Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

node.js - 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" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...