简体   繁体   English

快递中req和res的类型?

[英]Types for req and res in express?

In this demo I'm attempting to use the DefintelyTyped Response and Request types for the req, res parameters.在这个演示中,我尝试对req, res参数使用 DefintelyTyped ResponseRequest类型。 However this does not compile:但是,这不会编译:

const express = require('express');
const app = express();
app.get('/', (req:Request, res:Response) => {
    res.send('Hello Express Lovers!');
});
app.listen(3000, () => console.log('server started'));

The error is:错误是:

           ^
TSError: ⨯ Unable to compile TypeScript:
index.ts:4:9 - error TS2339: Property 'send' does not exist on type'Response'.

You should import Express the TypeScript way so its types (in @types/express ) come along, allowing the types of req and res to be inferred from app.get :您应该以 TypeScript 方式导入 Express,以便其类型(在@types/express中)出现,从而允许从app.get推断reqres的类型:

import * as express from 'express';
const app = express();
app.get('/', (req, res) => {
    res.send('Hello Express Lovers!');
});
app.listen(3000, () => console.log('server started'));

updated demo更新的演示

If you wanted to type them explicitly anyway, you would have to import the types:如果您想显式键入它们,则必须导入类型:

import * as express from 'express';
import {Request, Response} from 'express';
const app = express();
app.get('/', (req: Request, res: Response) => {
    res.send('Hello Express Lovers!');
});
app.listen(3000, () => console.log('server started'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 这是如何运作的? Express(err,req,res,next)或(req,res,next)中使用的可选第一个参数 - How does this work? Optional first argument used in Express (err, req, res, next) or (req, res, next) Express 4 Multer / req.body和res.json未定义 - Express 4 Multer / req.body and res.json not defined Express.js - 设置 res.locals 会改变 req 对象 - Express.js - Setting res.locals changes the req object 为什么我需要将 (req, res, next) 传递给 Express 中的 bodyParser? - Why do I need to pass (req, res, next) to bodyParser in Express? Express回调比(req,res)需要更多的参数 - Express callback needs more parameters than (req, res) 从 controller 中的方法响应,无需请求,来自 Express - Respond from method in controller without req, res from Express 使用Reactjs将Express req和res数据传递给客户端 - Pass Express req and res data to client using Reactjs Express app.all声明re / res与否 - Express app.all declaring req/res vs not Node + Express:Express 是否为每个请求处理程序克隆 req 和 res 对象? - Node + Express: Does Express clone the req and res objects for each request handler? 可以在不使用中间件函数的情况下增强express.js req和res变量吗? - It is possible to enhance the express.js req and res variables without using a middleware function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM