node.js - Expressjs 和 TypeScript - 无法输入 express
问题描述
我正在尝试使用 express 和 TypeScript 正确键入 nodejs 应用程序。考虑这段代码:
import express, { Router } from "express";
import { DeviceController } from "../controller/device.controller";
export class DeviceRouter {
public router: Router;
private deviceController: DeviceController;
constructor() {
this.deviceController = new DeviceController();
this.router = express.Router();
this.router.get("/", this.deviceController.index);
this.router.post("/", this.deviceController.create);
this.router.delete("/:id", this.deviceController.delete);
}
}
这会导致错误
TSError: ⨯ Unable to compile TypeScript:
src/module/device/router/device.router.ts:13:17 - error TS2339: Property 'get' does not exist on type 'Router'.
13 this.router.get("/", this.deviceController.index);
~~~
src/module/device/router/device.router.ts:14:17 - error TS2339: Property 'post' does not exist on type 'Router'.
14 this.router.post("/", this.deviceController.create);
~~~~
src/module/device/router/device.router.ts:15:17 - error TS2339: Property 'delete' does not exist on type 'Router'.
15 this.router.delete("/:id", this.deviceController.delete);
~~~~~~
当然,当键入路由器时,any
一切都按预期工作。我在打字时遇到了同样的问题app
,首先是一切正常时的代码示例:
import express from "express";
class App {
public app: any;
constructor() {
this.app = express();
}
}
export default new App().app;
以及键入导致错误时的示例:
import express, { Application } from "express";
class App {
public app: Application;
constructor() {
this.app = express();
}
}
export default new App().app;
结果:
src/server.ts:5:5 - error TS2339: Property 'listen' does not exist on type 'Application'.
5 app.listen(PORT, () => console.log(`App listening on port ${PORT}!`));
我的配置:
macOS Catalina 10.15.2 node.js v10.16.0
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": ["node_modules/*"]
}
},
"include": ["src/**/*"]
}
相关依赖:
"dependencies": {
"express": "~4.17.1"
},
"devDependencies": {
"@types/express": "~4.17.2",
"@types/node": "~13.5.0",
"ts-node": "~8.6.2",
"typescript": "~3.7.5"
}
解决方案
推荐阅读
- awk - 结合 awk 智能范围和 jq
- arrays - Mapbox GL JS:基于多维数组构建匹配表达式
- c++ - 用于检测车辆 OpenCV C++ 的 Group Rectangles 函数
- python - 如何使 Bokeh Datatable 响应式地适应
- python - 如何在熊猫中将字符串日期转换为数字
- python - 将会员鼠标与 Zapier 集成
- azure - Azure Functions 筛选器功能正式发布
- visual-studio - 解决方案的源代码控制信息之间似乎存在差异
- apache - 关于 Json Facet 聚合的 Solr-Filter
- excel - 在非标准表中使用索引匹配