我想用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
都不是。此类型不可为空。创建此类的实例时,如何在不给变量赋值的情况下声明该变量?
答案 0 :(得分:3)
如评论中所述,您的httpServer
字段可以是null
,也可以是 null
,在调用startListening
之前。
因此,您必须在类型声明中指定以下内容:
public httpServer: Server | null;
,然后通过其他方法处理null
种情况:
public stopListening(): void
{
if (this.httpServer === null) {
throw "Not listening, call "startListening()" first";
}
this.httpServer.close();
}