Typescript 在方法中设置 Class 本身的值,继承自基 Class

Typescript Set Value of Class itself in Method, Inheritance from Base Class

如何在其自己的方法中设置 class 本身的值?尝试利用 this。收到以下错误。

export class ProductForm extends FormGroup {

    constructor(){
      super({
        productName: new FormControl()
      })
    }
   
    addMoreFieldsTest(): void {
      this = {
        productName: new FormControl(),
        productDescription: new FormControl()
     }
}

Error: The left-hand side of an assignment expression must be a variable or a property access.

我可以使用 AddControl 方法,但是为了学习目的我想设置 class 本身。

更新答案

FormControl 的控件并不直接位于 FormGroup class 上,而是位于名为 controls

的 class 上的 属性 内部

因此,如果您只想添加到扩展 class 上的控件,您只需操作控件 属性.

    export class ExtendedFormGroup extends FormGroup {
      constructor(
        controls: { [k: string]: AbstractControl },
        validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions,
        asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]
      ) {
        super({...controls, alwaysPresent: new FormControl()}, 
               validatorOrOpts, 
               asyncValidator
        );
        this.extendedProperties();
      }
    
      extendedProperties() {
        this.controls["additional_control"] = new FormControl("");
      }
    }

上面的示例做了两件事

  • 将构造函数参数传递给 super,并在控件上添加一个额外的始终存在的项目。
  • 直接操作 controls 属性,如您的原始问题所示。

现在只需调用 new ExtendedFormGroup({}) 即可创建一个具有两个预定义控制器 alwaysPresentadditional_control

的 FormGroup

旧回复

由于 JavaScript,因此 TypeScript 通过扩展实现 classes 的方式基本上只是带有原型的标记块,您可以使用方括号表示法来访问属性this 你的范围 class.

    class Parent {
      foo: string;
      constructor(foo: string) {
        this.foo = foo;
      }
    }
    
    class Child extends Parent {
      constructor(foo: string) {
        super(foo);
        this.assignPropertiesDirectly();
      }
    
      assignPropertiesDirectly() {
        this["bar"] = "Creates 'bar' on Child";
        this["foo"] = "overwrites foo with this text";
      }
    }

但是,这种方法很脆弱,因为它不仅首先完全违背了使用 TypeScript 的目的,而且还依赖于为 属性 名称键入字符串值,这充其量会很麻烦维护,最坏的情况是容易出错。

在我看来,你的问题可能很适合作曲设计。