参数化方法,用于初始化typescript类中的变量

时间:2018-02-13 10:08:47

标签: angular typescript initialization code-reuse modularity

我的constructor中有以下代码来初始化变量。

public Elements: Observable<dcElementDataStoreItem>;
private elementSubjectData: BehaviorSubject<dcElementDataStoreItem>;

constructor() {
  this.elementSubjectData = new BehaviorSubject([]) as BehaviorSubject<ElementDataStoreItem>;
  this.Elements = this.elementSubjectData.asObservable();
}

现在只有2行,我可能有几个类似的项目。 所以我可以做类似下面的代码,(但这不起作用)

constructor() {
  this.initSubjectData<dcElementDataStoreItem>(this.elementSubjectData, this.Elements);
}

private initSubjectData<T>(privateList: BehaviorSubject<T>, publicList: Observable<T>) {
  privateList = new BehaviorSubject([]) as BehaviorSubject<T>;
  publicList = privateList.asObservable();
}

这样我就可以重用这个initSubjectData来初始化所有其他可能的方法

1 个答案:

答案 0 :(得分:1)

您不能像在其他语言中那样“通过引用”传递字段,但您可以传入字段名称并通过索引访问。由于Typescript支持作为另一种类型的键的类型的概念,因此这将是类型安全的。

public elementSubjectData: BehaviorSubject<ElementDataStoreItem>;
public Elements: Observable<ElementDataStoreItem>;
constructor() {
    this.initSubjectData("elementSubjectData", "Elements");
}

private initSubjectData(privateListField: keyof this, publicListField:  keyof this) {
    let privateList =  new BehaviorSubject([]);
    this[privateListField] = new BehaviorSubject([]) as any;
    this[publicListField] = privateList.asObservable() as any;
}

这种方法存在两个问题:

  1. 没有关于字段类型的检查
  2. 必须公开属性才能使该字段成为keyof
  3. 如果我们添加第二个函数来返回字段的类型化表示,我们可以修复数字1:

    interface Field<TName, TType> {
        name: string;
        set(value: TType) : void;
    }
    // In the class
    constructor() {
        this.initSubjectData(this.field("elementSubjectData"), this.field("Elements"));
    }
    field<TKey extends keyof this>(name: TKey): Field<TKey, this[TKey]> {
        return {
            name,
            set: (value) => {
                this[name] = value
            }
        };
    }
    private initSubjectData<T>(privateListField: Field<keyof this, BehaviorSubject<T>>, publicListField:  Field<keyof this, Observable<T>>) {
        let privateList = new BehaviorSubject([]) as BehaviorSubject<T>;
        privateListField.set(privateList);
        publicListField.set(privateList.asObservable());
    }