首页 > 解决方案 > 类中的 TypeScript 接口方法实现

问题描述

所以我有这个奇怪的观察,并希望对此有所了解,我已经制作了一些我用不同的类实现的接口,我发现了以下内容:

当我在此类 Revenue 中实现了作为 TaxableLineItem 接口一部分的方法时,我能够在实现接口的方法 (applyTax) 时更改参数,即参数类型为 (input :TaxRate) 而不是指定的 (input : 输入)

interface LineItem {
  getAmount(): number;
  getType(): ELineItemType;
  applyForecast(input?: Input, prevCFLineItem?: LineItem): void;
}
interface TaxableLineItem{
  applyTax(input: Input): void;
  getPostTaxAmount(): number;
}

class Revenue implements LineItem, TaxableLineItem{
    private amount: number;
    private postTaxAmount: number;
    private type: ELineItemType;
    
    /**other implemented methods and constructor*/

    applyTax(input: TaxRate): void {
      this.postTaxAmount = this.amount * input.getResidualMargin();
   }
      
}

我觉得这是可行的,因为我已经在 TaxRate 类中实现了 Input 接口,如下所示:

interface Input {
  getVariableAmount(): number;
}

class TaxRate implements Input, IMargin {
  private taxRate: number;
  constructor(taxRate: number) {
    this.taxRate = taxRate;
  }
  getResidualMargin(): number {
    return 1 - this.taxRate;
  }
  getVariableAmount(): number {
    return this.taxRate;
  }
}

我的猜测是,因为 TaxRate 实现 Input , ts 编译器接受该收入实现 applyTax 方法

对此还有其他解释吗?

标签: typescriptoop

解决方案


推荐阅读