TypeScript类中如何返回express实例?new实例调用express方法报错如何解决
问题原因
TypeScript 默认会将 new 类() 的返回值推导为该类的实例类型,即使你在构造函数中手动返回了 express 的 app 实例,类型系统也不会自动识别为 Express 类型,因此会提示找不到 get 方法。
解决方案
以下两种方案都可以保留类的实现方式:
方案1:显式声明构造函数返回类型
直接给 Server 类的构造函数指定返回值为 Express 类型,无需修改 index.ts 的代码:
// server.ts import express, { Express } from "express"; import OutputLevel from "../types/OutputLevels"; class Server { /** * Creates an express web server * @param {Number} port The port the server is listening on * @param {OutputLevel} [outputLevel] The level of console output (commonly based on CLI arguments) {@link OutputLevel} * @returns {Express} */ constructor(port: Number, outputLevel?: OutputLevel): Express { const app = express(); app.listen(port, () => { if (outputLevel && outputLevel >= 2) console.log(`[Server @ ${port}] Listening @ http://localhost:${port}`); }); return app; } } export default Server;
方案2:将express实例挂为类属性(更推荐)
符合面向对象设计规范,后续扩展功能更方便,不会出现类型混淆问题:
// server.ts import express, { Express } from "express"; import OutputLevel from "../types/OutputLevels"; class Server { public app: Express; /** * Creates an express web server * @param {Number} port The port the server is listening on * @param {OutputLevel} [outputLevel] The level of console output (commonly based on CLI arguments) {@link OutputLevel} */ constructor(port: Number, outputLevel?: OutputLevel) { this.app = express(); this.app.listen(port, () => { if (outputLevel && outputLevel >= 2) console.log(`[Server @ ${port}] Listening @ http://localhost:${port}`); }); } } export default Server;
对应修改index.ts,访问实例下的app属性即可:
// index.ts import Server from "./server/server"; import OutputLevel from "./types/OutputLevels"; let server = new Server(2020, OutputLevel.INFO); server.app.get("/", (req, res) => { res.send("hello world") });
内容的提问来源于stack exchange,提问作者Delight
相关产品推荐
相关产品推荐

