为默认值分配默认值的最佳方法

时间:2017-03-23 15:21:12

标签: typescript

例如我有这个:

  class SomeClass{
    private font:GameConfFont;
    init = () => {
      this.font = data.game.font || <GameConfFont>{};
    }
  }

GameConfFont是:

declare interface GameConfFont {
  families: Array<string>,
  css: string,
}

我不喜欢我必须在这里明确地转换默认值,这个<GameConfFont>{},但如果我不这样做,那么TS会抱怨它。有没有其他更优雅的方式来写它?

2 个答案:

答案 0 :(得分:2)

空对象({})不是有效的GameConfFont。它缺少必需的属性。为什么要在GameConfFont中保留无效的this.font?如果您希望GameConfFont上的属性是可选的,则将其声明为:

interface GameConfFont {
  families?: Array<string>,
  css?: string,
}

另一种选择可能是将this.font初始化为null。

答案 1 :(得分:1)

也许将您的GameConfFont声明为类并使用其构造函数?

class GameConfFont
{
    constructor()
    {
        //Initialize default instance here
    }

    public name: string;
}

class SomeClass
{
    private font:GameConfFont;

    public init(data)
    {
       this.font = data.game.font || new GameConfFont();
    }
}
相关问题