Search code examples
node.jstypescriptexpressdefinitelytyped

DefinitelyTyped definitions for Express not working


I'm trying to get a Hello World express app running in node with typescript, and the DefinitelyTyped types just appear to be completely ignored.

package.json:

{
    "dependencies": {
        "@types/express": "*",
        "@types/node": "*",
        "express": "*"
    }
}

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "lib": [
            "es2015"
        ],
        "target": "es6",
        "noImplicitAny": true,
        "strictNullChecks": true,
        "noImplicitThis": true,
        "noImplicitReturns": true,
        "moduleResolution": "node",
        "outDir": "dist",
        "baseUrl": "."
    },
    "include": [
        "src/**/*"
    ]
}

src/app.ts:

const express = require('express'); //express is typed "any" because @types/express is apparently ignored
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello World!')); //Compile error here because implicit any
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Compile output:

~/tmp/ws-test$ tsc
src/app.ts(5,15): error TS7006: Parameter 'req' implicitly has an 'any' type.
src/app.ts(5,20): error TS7006: Parameter 'res' implicitly has an 'any' type.

I feel like I'm taking crazy pills. What's wrong here?


Solution

  • In your particular setup, you'll have to do imports in one of two ways:

    import express = require('express');
    

    or:

    import * as express from 'express';
    

    If you wan't imports like:

    import express from 'express';
    

    You can add "allowSyntheticDefaultImports": true to the compilerOptions.