【问题标题】:declaring a variable without assigning a value in the constructor when creating an instance创建实例时在构造函数中声明变量而不赋值
【发布时间】:2019-08-26 08:05:45
【问题描述】:

我想用 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 也不是。此类型不可为空。在创建这个类的实例时如何声明这个变量而不给它赋值?

【问题讨论】:

  • 如果你只是在稍后的某个时间分配一个值,那么有可能处于值是 null/不存在的状态,所以你必须 将类型声明为可为空/可选。
  • hm 问题是 Server 类型来自 Nodes http 模块所以我没有创建这个变量类型

标签: javascript node.js typescript express


【解决方案1】:

如 cmets 中所述,您的 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多