首页 > 解决方案 > 为什么在这种情况下重载方法会引发错误?

问题描述

我尝试实现的简单重载示例,但出现错误。A 和 B 实现 IB。A 在构造函数中创建 B。然后在它自己的map方法中调用b的map方法。

以下是错误案例的示例:

it('testOverloading', () =>
{
    interface IB
    {
        map(a: number): number;
        map(b: string): string;
    }

    class B implements IB
    {
        map(a: number): number
        map(b: string): string;
        map(a: number | string): number | string
        {
            return typeof a === "string" ? "aaa" : 555;
        }
    }

    class A implements IB
    {
        private b:B;

        constructor()
        {
            this.b = new B();
        }

        map(a: number): number
        map(b: string): string;
        map(a: number | string): number | string
        {
            return this.b.map(a);
        }

    }

    const o = new A();
    logger.debug(o.map("asd"));
    logger.debug(o.map(123));
});

错误:

TSError: ⨯ Unable to compile TypeScript:
test/AppFactoryTest.ts(60,31): error TS2769: No overload matches this call.
  Overload 1 of 2, '(a: number): number', gave the following error.
    Argument of type 'string | number' is not assignable to parameter of type 'number'.
      Type 'string' is not assignable to type 'number'.
  Overload 2 of 2, '(b: string): string', gave the following error.
    Argument of type 'string | number' is not assignable to parameter of type 'string'.
      Type 'number' is not assignable to type 'string'.

我错过了什么?

UPD: 我已经设法通过在 B 类中添加额外的行来修复它

map(a: number | string): number | string;

但我仍然不明白为什么要这样做。任何解释将不胜感激!

标签: typescriptoverloading

解决方案


推荐阅读