[英]declaring a variable without assigning a value in the constructor when creating an instance
我想用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
並且在調用startListening
之前也為 null
。
因此你必須在類型聲明中指定如下:
public httpServer: Server | null;
然后在其他方法中處理null
情況:
public stopListening(): void
{
if (this.httpServer === null) {
throw "Not listening, call "startListening()" first";
}
this.httpServer.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.