簡體   English   中英

在創建實例時聲明變量而不在構造函數中賦值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM