【发布时间】: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类型来自 Nodeshttp模块所以我没有创建这个变量类型
标签: javascript node.js typescript express