【问题标题】:Typescript interface default that will get overridden in constructorTypescript 接口默认值将在构造函数中被覆盖
【发布时间】:2018-04-20 22:55:49
【问题描述】:

我有一个具有matchMaker 属性的接口,它看起来像这样:

export interface ServerOptions {
  matchMaker: MatchMakerType<MatchMaker>
}

然后我有一个类,它设置默认值以利用该接口,如下所示:

export class Server {
  public readonly settings: ServerOptions = {
    matchMaker: undefined
  }

  public constructor(options: ServerOptions) {
    this.settings = Object.assign(this.settings, options)
  }
}

当创建类Server 的新实例时,我希望在将选项传递给构造函数时为matchMaker 设置typeof MatchMaker。我不想让undefined | null 或其他任何东西传递给构造函数,但是我需要有一些值作为默认值,当我使用undefined 时会被覆盖,我得到一个错误:

类型“未定义”不可分配给类型“MatchMakerType”。

如何设置将被覆盖的默认值?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您可以使用Partial,以允许Server.settings 中未定义的属性:

     public readonly settings: Partial<ServerOptions> = {  }
    

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 2021-06-06
      • 2016-05-06
      • 1970-01-01
      相关资源
      最近更新 更多