Typescript 如何避免类中的代码重复?

Typescript 如何避免类中的代码重复?,typescript,typescript2.0,Typescript,Typescript2.0,我有两个扩展抽象类的类: class SubstitutionTeacher extends SubstitutionAbstract { abstract _save(); } class SubstitutionFree extends SubstitutionAbstract { public _save() { } } class SubstitutionSubject extends Substitution

我有两个扩展抽象类的类:

   class SubstitutionTeacher extends SubstitutionAbstract {
      abstract _save();
    }

    class SubstitutionFree extends SubstitutionAbstract {
      public _save() {
      }
    }

    class SubstitutionSubject extends SubstitutionAbstract {
      public _save() {
      }
    }
在方法
save()
中,我意识到自己的行为如下:

  /* Class SubstitutionFree
    public _save() {

        const substitutionAdd: ISubstitutionModelTeacher = {
          lesson: this.substitution.lessonNumber,
          confirmed: true,
          subsDate: this.substitution.date,
          newTeacher: this.substitution.teacher
        };

        return this.replaceService.addSubstitution(substitutionAdd);
      }

 /* Class SubstitutionSubject
    public _save() {

        const substitutionAdd: ISubstitutionModelTeacher = {
          lesson: this.substitution.lessonNumber,
          confirmed: true,
          newTeacher: this.substitution.teacher
        };

        return this.replaceService.addSubstitution(substitutionAdd);
      }
正如您所看到的,这两种方法几乎相似。我想避免这种重复:

{ lesson: this.substitution.lessonNumber,
confirmed: true,
newTeacher: this.substitution.teacher
}

我可以将
save()
更改为常规
save()
,并在其中传递一个公共部分,但它失去了抽象的意义。

这可能是无效的typescript,因为我的typescript不太好:)

但是您的问题不是特定于typescript的,所以这可能会让您了解如何解决这些问题

SubstitutionAbstract
中创建一个方法:

class SubstitutionAbstract {

    // this one should be called each time you need that object instead of duplicating
    // you can make it protected if there is such stuff in typescript
    public getMyStuff(param1, param2, param3, param4) {
        return { lesson: param1,
                 confirmed: param2,
                 newTeacher: param3,
                 subsDate: param4
               };
    }  
    // .....
}
在每个子类中,只需将其称为:

public _save() {
    const substitutionAdd: ISubstitutionModelTeacher = 
             getMyStuff(this.substitution.lessonNumber, true, 
                           this.substitution.date, this.substitution.teacher);

    return this.replaceService.addSubstitution(substitutionAdd);
}
如果在某些实现中不需要
subdate
,则将该实现的
null
传递给
getMyStuff
,不要认为这可能是个问题。Typescript可能会检查类型等,因此您可能需要使用该方法才能工作(例如,它应该返回类型为
issubstitutionmodelsteacher
的内容)

再说一遍,这可能是不起作用的代码,因为typescript不是我的领域,但它描述了如何做的想法

当然还有其他方法,这只是一个例子


快乐编码:)

只需将其移动到某个方法,使该方法返回这些内容,并在需要时调用该方法即可。我想您可以将此方法添加到
SubstitutionAbstract
您的意思是要执行此方法而不是抽象,您可以共享一个示例吗?\n我可以执行以下操作:return IMode:={…para,eters}?或者类似这样:
return{}as IModel?这是一个特定于typescript的问题,我无法正确回答,抱歉)如果您不确定,请尝试这两种方法,并检查两种情况下代码的行为。也许没有区别。