Express 的 DefinitelyTyped 定义不起作用

DefinitelyTyped definitions for Express not working

我正在尝试使用 typescript 在节点中获取一个 Hello World Express 应用程序 运行,而 DefinitelyTyped 类型似乎被完全忽略了。

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}!`));

编译输出:

~/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.

我觉得我正在服用疯狂的药片。这里有什么问题?

在您的特定设置中,您必须通过以下两种方式之一进行导入:

import express = require('express');

或:

import * as express from 'express';

如果您不想导入:

import express from 'express';

您可以将 "allowSyntheticDefaultImports": true 添加到 compilerOptions