Express中req和res的类型是什么?

9
在这个演示中,我试图使用DefinitelyTyped的响应(Response)和请求(Request)类型来作为req、res参数。然而,这样不会编译成功。链接为:https://repl.it/@OleErsoy/Repl-Medium-Typescript-ExpressResponseRequest
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'));

错误信息如下:

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

它无法编译的是哪个错误?你导入了那些类型吗? - Ry-
是的 - @types/express - Ole
1
安装软件包只是使类型可供导入。本地软件包的存在本身不会导入类型。 - Ry-
Repl没有对我发出警告,所以我认为它们已经自动导入了...谢谢! - Ole
1个回答

17

你应该以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'));

更新演示

如果您仍然想要显式地输入它们,那么您需要导入这些类型:

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

1
使用 esModuleInterop 可以这样写: import express, { Request, Response } from 'express'。更加优美。 - Tyler Sebastian
你好,你是怎么知道req的类型是Request而res的类型是Response的?我查看了https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express中的所有**.d.ts文件,但没有找到任何提示。 - juexu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接