最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Types for req and res in express? - Stack Overflow

programmeradmin4浏览0评论

In this demo I'm attempting to use the DefintelyTyped Response and Request types for the req, res parameters. 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'.

In this demo I'm attempting to use the DefintelyTyped Response and Request types for the req, res parameters. 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'.
Share Improve this question edited Oct 26, 2019 at 1:02 Ole asked Oct 26, 2019 at 0:37 OleOle 46.9k68 gold badges237 silver badges441 bronze badges 4
  • Which error does it not compile with? Did you import those types? – Ry- Commented Oct 26, 2019 at 0:54
  • Yes - @types/express – Ole Commented Oct 26, 2019 at 1:01
  • 1 Installing a package just makes the types available to import. The existence of a local package does not import types on its own. – Ry- Commented Oct 26, 2019 at 1:02
  • Repl didn't bark at me so I thought they were auto imported ... Thanks! – Ole Commented Oct 26, 2019 at 1:11
Add a comment  | 

1 Answer 1

Reset to default 19

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:

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'));
发布评论

评论列表(0)

  1. 暂无评论