【发布时间】:2021-02-15 11:49:41
【问题描述】:
我正在尝试文档附带的express route handlers 以特定顺序进行一系列函数调用,所以我想将一个值从cb0 传递给cb1(或cb2),目前我在 req 对象中设置一个属性并从另一个处理程序访问它,这工作正常。
const express = require('express');
const app = express();
const PORT = 8000;
const cb0 = function (req, res, next) {
console.log('CB0');
req.cb0val = 'Hello';
next();
}
const cb1 = function (req, res, next) {
console.log('CB1');
req.cb1val = 'World';
next();
}
const cb2 = function (req, res) {
res.send(`Hey, ${req.cb0val} ${req.cb1val}`);
}
app.get('/', [cb0, cb1, cb2])
app.listen(PORT, () => {
console.log(`⚡️[server]: Server is running at https://localhost:${PORT}`);
});
使用typescript时出现问题
import express from 'express';
const app = express();
const PORT = 8000;
const cb0: express.RequestHandler = function (req: express.Request, res: express.Response, next: Function) {
console.log('CB0');
req.cb0val = 'Hello';
next();
}
const cb1: express.RequestHandler = function (req: express.Request, res: express.Response, next: Function) {
console.log('CB1');
req.cb1val = 'World';
next();
}
const cb2: express.RequestHandler = function (req: express.Request, res: express.Response) {
res.send(`Hey, ${req.cb0val} ${req.cb1val}`);
}
app.get('/example/c', [cb0, cb1, cb2])
app.listen(PORT, () => {
console.log(`⚡️[server]: Server is running at https://localhost:${PORT}`);
});
因为我将req 的类型设置为express.Request,所以我无法设置该类型的新属性,出现以下错误:
index.ts:7:7 - error TS2339: Property 'cb0val' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.
7 req.cb0val = 'Hello';
~~~~~~
index.ts:13:7 - error TS2339: Property 'cb1val' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.
13 req.cb1val = 'World';
~~~~~~
index.ts:18:24 - error TS2339: Property 'cb0val' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.
18 res.send(`Hey, ${req.cb0val} ${req.cb1val}`);
~~~~~~
index.ts:18:38 - error TS2339: Property 'cb1val' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.
18 res.send(`Hey, ${req.cb0val} ${req.cb1val}`);
~~~~~~
在不将express.Request 的类型更改为any 的情况下,处理这种情况的正确方法是什么?
【问题讨论】:
标签: typescript express