Typescript如何声明一个返回最小公分母类型的函数?

时间:2019-06-25 09:05:20

标签: typescript2.0 declare

我想声明一个返回普通类型或其扩展类型的函数

interface Common {
  id: number;
}

interface AdditionalInformation extends Common {
  myname: string;
}

该函数肯定会返回一个包含 id 属性

的对象

并希望它也可以返回 myname 属性

我试图这样声明函数:

export class Lib {

  public static lowestCommonDenominator <T extends Common>(): Common {
    const a: Common = { id: 1 };
    return a;
  }

  public static firstCaseFunction(): Common {
    const ok: Common = this.lowestCommonDenominator();
    return ok;
  }

  public static secondCaseFunction(): AdditionalInformation {
    // Property 'myname' is missing in type 'Common' but required in type 'AdditionalInformation'.ts(2741)
    const ko: AdditionalInformation = this.lowestCommonDenominator();
    return ko;
  }

}

但是当我将函数分配给扩展类型时,会出现错误:

  

类型“公用”中缺少属性“ myname”,但类型中为必需   'AdditionalInformation'.ts(2741)

是否可以实现我想要的?

1 个答案:

答案 0 :(得分:1)

此代码段可消除错误

export class Lib {
  public static lowestCommonDenominator <T extends Common>(): T {
    const a: Common = { id: 1 };
    return a as T;
  }

  public static firstCaseFunction(): Common {
    const ok: Common = this.lowestCommonDenominator();
    return ok;
  }

  public static secondCaseFunction(): AdditionalInformation {
     const ko: AdditionalInformation = this.lowestCommonDenominator<AdditionalInformation>();
    return ko;
  }
}