Types for req and res in express?

Viewed 8057

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'.
1 Answers

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