简体   繁体   English

Typescript接口默认会在构造函数中被覆盖

[英]Typescript interface default that will get overridden in constructor

I have an interface that has a property matchMaker , it looks like this: 我有一个具有属性matchMaker的接口,它看起来像这样:

export interface ServerOptions {
  matchMaker: MatchMakerType<MatchMaker>
}

I then have a class that sets up default values for to utilize that interface which looks like this: 然后我有一个类设置默认值,以利用该界面,如下所示:

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

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

When a new instance of the class Server is created, I want to require a typeof MatchMaker to be set for matchMaker when passing the options to the constructor. 当创建类Server的新实例时,我想要在将选项传递给构造函数时为matchMaker设置一个类型的typeof MatchMaker I don't want to allow undefined | null 我不想允许undefined | null undefined | null or anything else to be passed to the constructor, however I need to have some value as the default, and when I use undefined which will get overridden, I get an error: undefined | null或其他任何要传递给构造函数的东西,但是我需要有一些值作为默认值,当我使用undefined会被覆盖,我得到一个错误:

Type 'undefined' is not assignable to type 'MatchMakerType'. 类型'undefined'不能分配给'MatchMakerType'类型。

What can I do to set up a default that will be overridden? 如何设置将被覆盖的默认值?

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

 public readonly settings: Partial<ServerOptions> = {  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM