首页 > 解决方案 > util方法的静态字段或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.*和自动完成,但创建一个实际上永远不会被实例化的类似乎“丑陋”。我更多地将它用作命名空间。

另外,它对摇树有影响吗?未使用的验证器会在构建时被抑制吗?

标签: angulartypescript

解决方案


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


推荐阅读