本文介绍了如何将Typescript定义添加到Express req&资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一套用于REST API的控制器功能,并且我收到了很多以下内容

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.

res类似.我一直在玩打字等,但没有成功.例如,下面的Request类型参数不起作用.

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) => {

我尝试将import * as express from "express";添加到文件中-我通常不需要它,因为这些功能是由实际上实现路由的index.js导出和使用的.

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.

这是tsd.d.ts

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" />

推荐答案

您可以使用名为import的ES6样式仅导入所需的接口,而不是包含表达自身的import * as express from 'express'.

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.

首先请确保已安装express(npm install -D @types/express)的类型定义.

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

示例:

// 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);

当前使用TypeScript 2.3.4和@ types/express 4.0.36.

Currently using TypeScript 2.3.4 and @types/express 4.0.36.

我有同样的问题,所以我想我会提供一个答案,以防其他人遇到这个问题.

I had the same question so I thought I'd provide an answer in case anyone else comes across this.

这篇关于如何将Typescript定义添加到Express req&amp;资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 07:13