Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 2.2 Express req, res implicitly any

I'm struggeling a bit with adding types to a node/express project.

I'm using TypeScript 2.2 and express 4.x and I've installed types through npm:

npm install --save-dev @types/express

import * as express from "express"

const app: express.Application = express()

app.get("/hello", (req, res) => {
  res.send("world")
})

This gives me:

src/app.ts(33,22): error TS7006: Parameter 'req' implicitly has an 'any' type.
src/app.ts(33,27): error TS7006: Parameter 'res' implicitly has an 'any' type.

I'm trying to avoid having to do this for all request handlers:

(req: express.Request, res: express.Response) => {} 

In my mind it should able to infer those. Am I wrong? Is that not possible?

tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "noImplicitAny": true,
    "sourceMap": true,
    "outDir": "dist",
    "typeRoots": ["src/types", "node_modules/@types"]
  },
  "include": [
    "src/**/*.ts"
  ]
}

Thanks!

like image 355
janneh Avatar asked Mar 02 '17 16:03

janneh


2 Answers

Try adding Express type

import {Express} from 'express'
var express = require('express')

const app:Express = express();

app.get('/test', (req, res) => {
  res.send({ message: 'Welcome to Express!' });
});
like image 171
nivendha Avatar answered Nov 13 '22 09:11

nivendha


The express library's get method is too heavily overloaded (see here for demo https://github.com/DefinitelyTyped/DefinitelyTyped/blob/14cfa9f41c2835fcd22e7243a32b25253c310dee/express-serve-static-core/index.d.ts#L25-L40)

interface RequestHandler {
    (req: Request, res: Response, next: NextFunction): any;
}

interface ErrorRequestHandler {
    (err: any, req: Request, res: Response, next: NextFunction): any;
}

type PathParams = string | RegExp | (string | RegExp)[];

type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[];

interface IRouterMatcher<T> {
    (path: PathParams, ...handlers: RequestHandler[]): T;
    (path: PathParams, ...handlers: RequestHandlerParams[]): T;
}

The RequestHandlerParams is making it impossible to be reliably sure about what req and res have. Suggestion: just annotate it for now

like image 28
basarat Avatar answered Nov 13 '22 08:11

basarat