[英]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 Response
和Request
类型。 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
推断req
和res
的类型:
import * as express from 'express';
const app = express();
app.get('/', (req, res) => {
res.send('Hello Express Lovers!');
});
app.listen(3000, () => console.log('server started'));
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.