Express的DefinitelyTyped定义不起作用

时间:2019-01-11 15:40:00

标签: node.js typescript express definitelytyped

我正在尝试使一个带有Typescript的Hello World Express应用程序在node中运行,而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.

我觉得我正在服用疯狂药丸。怎么了?

1 个答案:

答案 0 :(得分:1)

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

import express = require('express');

或:

import * as express from 'express';

如果您不想导入:

import express from 'express';

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