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

标签 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 中为其分配了一个值。但是我不能在构造函数中将 null 分配给它。 undefined 两者都不是。此类型不可为空。如何在创建此类的实例时声明此变量而不为其赋值?

最佳答案

如评论中所述,您的 httpServer 字段可以是 null 并且 is 在调用之前 nullstartListening

因此你必须像这样在类型声明中指定:

public httpServer: Server | null;

然后在进一步的方法中处理 null 情况:

public stopListening(): void 
{
  if (this.httpServer === null) {
    throw "Not listening, call "startListening()" first";
  }
  this.httpServer.close();
}

关于javascript - 创建实例时在构造函数中声明变量而不赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57654015/

相关文章:

javascript - Discord.js permissionOverwrites 不起作用但完全没有错误

javascript - 无法对 type=number 的输入字段应用限制

javascript - Facebook JS SDK 滚动

javascript - 如何解析这种自制的基于字符串的数据格式?

javascript - 无法使用 Cypress 获取 vuex 状态

javascript - Angular 7 分量

angular - ionic 2 beta 8 设置根页面无法导航

javascript - bxslider水平淡入淡出效果

node.js - 生产环境配置ghost blog

javascript - NPM 脚本需要准确的文件名