util方法的静态字段或const函数?

时间:2018-10-16 17:12:15

标签: angular typescript

我需要创建一组可重复使用的验证器。

将它们声明为静态const函数更好吗?

export const emailValidator: ValidatorFn = 
  function(control: AbstractControl): {[key: string]: any} | null {
    return [...];
  };

export const anotherValidator: ValidatorFn = 
  function(control: AbstractControl): {[key: string]: any} | null {
    return [...];
  };

还是作为非实例化类的静态方法?

class CustomValidators {

  static emailValidator = 
    function(control: AbstractControl): {[key: string]: any} | null {
      return [...];
    }

  static anotherValidator = 
    function(control: AbstractControl): {[key: string]: any} | null {
      return [...];
    }
}

第二个解决方案看起来不错,因为我将能够使用CustomValidators.*和自动完成功能,但是创建一个实际上永远不会实例化的类似乎很“丑陋”。我将它更多地用作命名空间。

还对摇树有影响吗?在构建时会抑制未使用的验证器吗?

1 个答案:

答案 0 :(得分:1)

静态对象将始终保留在javascript发出的捆绑软件中,以便随时可以用作对象。如果您愿意,可以在util函数中编写那些函数,这些函数可以按需创建验证器,而不是将它们预先初始化为静态对象。 另一种方法是创建名称空间并按需初始化。