node.js - 如何将 Typescript 定义添加到 Express req 和 res

标签 node.js express typescript

我有一组用于我的 REST API 的 Controller 函数,我得到了很多以下内容

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

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

这是 Controller 文件的示例。引用路径正确。

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

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

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

最佳答案

您可以使用 ES6 样式命名的导入来仅导入您需要的接口(interface),而不是 import * as express from 'express' 这将包括 express 本身。

首先,确保您已经安装了 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。

关于node.js - 如何将 Typescript 定义添加到 Express req 和 res,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34508081/

相关文章:

node.js - 在 Angular 2 typescript 中包含 lib 时找不到模块 "shelljs"

javascript - 尝试在 node-js/express 中代理图像

node.js - 未收到从 azure-event-hubs onMessage 函数发送的 azure-iothub 消息

javascript - 响应.on 是什么意思? Node.js

node.js - HTTP响应发送后如何记录HTTP请求/响应信息?

html - TypeScript:类型系统的问题

node.js - 我应该在 NPM package.json 中将 "start"脚本设置为什么?

node.js - 按名称的Mongodb请求呈现错误的数据

node.js - Req.session 在请求内未定义?

reactjs - 在react-testing-library和TypeScript中renderHook的合适类型是什么?