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

Javascript 在创建实例时声明变量而不在构造函数中赋值,javascript,node.js,typescript,express,Javascript,Node.js,Typescript,Express,我想用Typescript创建一个节点RESTAPI,并创建一个管理Express应用程序的基本类 import express from 'express'; import { Server } from 'http'; import { injectable } from 'inversify'; import { IWebServer } from './IWebServer'; import { RoutesLoader } from './routes/RoutesLoader';

我想用Typescript创建一个节点RESTAPI,并创建一个管理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
赋值给它<代码>未定义两者都没有。此类型不可为空。创建此类实例时,如何在不为其赋值的情况下声明此变量?

如注释中所述,
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();
}

如果您只是在稍后的某个时间分配一个值,则可能处于值为
null
/不存在的状态,因此必须将该类型声明为可空/可选。问题是类型
Server
来自节点
http
模块,因此我没有创建此变量类型