创建实例时在构造函数中声明变量而不分配值

时间:2019-08-26 08:05:45

标签: javascript node.js typescript express

我想用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中为其分配值。但是我无法在构造函数中为其分配nullundefined都不是。此类型不可为空。创建此类的实例时,如何在不给变量赋值的情况下声明该变量?

1 个答案:

答案 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();
}