【问题标题】:DefinitelyTyped definitions for Express not workingExpress 的绝对类型定义不起作用
【发布时间】:2019-01-12 02:03:38
【问题描述】:

我正在尝试使用 typescript 在 node 中运行 Hello World express 应用程序,而 DevelopedlyTyped 类型似乎被完全忽略了。

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 * as express from 'express';
  • Juraj,你赢了,成功了。看起来那些应该是相同的陈述,对吧?是否存在一些我不知道的语义差异?
  • 当我使用 require 而不是新的 es 导入时我没有类型,不知道为什么但我从未尝试过解决,我一直在使用 import...

标签: node.js typescript express definitelytyped


【解决方案1】:

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

import express = require('express');

或:

import * as express from 'express';

如果你不想像这样导入:

import express from 'express';

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2022-09-29
    • 2020-03-28
    相关资源
    最近更新 更多