node.js - Express 的绝对类型定义不起作用
问题描述
我正在尝试使用打字稿在节点中运行 Hello World express 应用程序,而DefinitelyTyped 类型似乎被完全忽略了。
包.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
.
推荐阅读
- pine-script - 如何为确定的数组值查找柱的交易量?
- node.js - Express 和 Pug:意外的标识符
- javascript - 我的警报仅在我的 React 和 Redux 应用程序的第二次尝试中出现
- c# - UserControl WPF 中的 DataContext 绑定
- python - 连接到代理不工作的网站(python)
- c++ - 我们可以使用pair作为向量的名称吗?
- r - 如何仅保存最近生成的图?
- scala - Spark 2.4 无法使用变量插入记录
- python - tkinter 文本框忽略索引
- python - 通过用户输入将列表传递给 pandas 查询