0
votes

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?

1
Can you show the build command and output? - Elliot Blackburn
try this: import * as express from 'express'; - Juraj Kocan
Juraj, you win, that did it. It seems like those should be identical statements, right? Is there some semantic difference I'm not aware of? - Ben Dilts
i have no type when i use require insteed of new es imports, not sure why but i have never been try to solve, i am always using import... - Juraj Kocan

1 Answers

5
votes

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.