我想用 Typescript 创建一个 Node REST API 并创建一个管理 Express 应用程序的基本类
import express from 'express';
import { Server } from 'http';
import { injectable } from 'inversify';
import { IWebServer } from './IWebServer';
import { RoutesLoader } from './routes/RoutesLoader';
import * as webServerConfig from '../../config/webServerConfig';
import { IPlugin } from './plugins/IPlugin';
import { LoggerPlugin } from './plugins/LoggerPlugin';
import { CorsPlugin } from './plugins/CorsPlugin';
import { BodyParserPlugin } from './plugins/BodyParserPlugin';
@injectable()
export class WebServer implements IWebServer {
public app: express.Application;
public httpServer: Server;
private port: any;
constructor () {
this.app = express();
this.httpServer = null;
this.port = webServerConfig.port;
}
public startListening(): void
{
const plugins: IPlugin[] = [
new LoggerPlugin(),
new CorsPlugin(),
new BodyParserPlugin()
];
for (const plugin of plugins) { // load all the middleware plugins
plugin.register();
}
new RoutesLoader(); // load all the routes
try {
this.httpServer = this.app.listen(this.port);
} catch (error) {
throw error;
}
}
public stopListening(): void
{
this.httpServer.close();
}
}
这段代码对我来说看起来不错,但问题是我必须在类构造函数中为 httpServer
赋值。如您所见,我稍后在 startListening
中为其分配了一个值。但是我不能在构造函数中将 null
分配给它。 undefined
两者都不是。此类型不可为空。如何在创建此类的实例时声明此变量而不为其赋值?
最佳答案
如评论中所述,您的 httpServer
字段可以是 null
并且 is 在调用之前 null
到 startListening
。
因此你必须像这样在类型声明中指定:
public httpServer: Server | null;
然后在进一步的方法中处理 null
情况:
public stopListening(): void
{
if (this.httpServer === null) {
throw "Not listening, call "startListening()" first";
}
this.httpServer.close();
}
关于javascript - 创建实例时在构造函数中声明变量而不赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57654015/