在Typescript中访问配置默认值?

时间:2018-09-22 18:24:49

标签: javascript typescript

我想知道是否有更有效/更紧凑的方式来做到这一点。我有一个配置类实例,其中所有状态都是可选的。看起来像这样。我有一个这样的构造函数(StoreConfig粘贴在下面):

constructor(config?:StoreConfig) {
    config = config ? config : new StoreConfig();

}

现在只需将配置与默认值getters一起使用。

/**
 * Store configuration.
 */
export class StoreConfig {
  static ID_KEY_DEFAULT:string = 'id';
  static GUID_KEY_DEFAULT:string = 'gid';

  constructor(private _idKey?:string, private _guidKey?:string) {};

  get idKey():string {
    return  this._idKey ? this._idKey : StoreConfig.ID_KEY_DEFAULT;
  }
  get guidKey():string {
    return this.guidKey ? this.guidKey : StoreConfig.GUID_KEY_DEFAULT;
  }
}

2 个答案:

答案 0 :(得分:1)

为构造函数参数使用默认值,如下所示:

export class StoreConfig {
  constructor(
    private _idKey: string = "id",
    private _guidKey: string = "gid"
  ) {}

  get idKey(): string {
    return this._idKey
  }
  get guidKey(): string {
    return this._guidKey
  }
}

通过提供默认值,可以让Typescript知道这是一个可选参数,并且会恢复为默认值。

那么当您执行此操作时,它就不会抱怨缺少参数:

const x = new StoreConfig()

答案 1 :(得分:0)

这对于我要使用的general design来说效果很好:

export const STORE_CONFIG_DEFAULT: StoreConfig = {
  idKey: "id",
  guidKey: "gid"
};

Object.freeze(STORE_CONFIG_DEFAULT);

export class StoreConfig {
  public idKey: string;
  public guidKey: string;
  constructor(c?: Partial<StoreConfig>) {
    let config = Object.assign({ ...STORE_CONFIG_DEFAULT }, c);
    this.idKey = config.idKey;
    this.guidKey = config.guidKey;
  }
}

现在其他一些类可以依赖STORE_CONFIG_DEFAULT进行默认配置。