首页 > 解决方案 > 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"
  }

标签: node.jstypescriptexpress

解决方案


推荐阅读