typescript - 为什么在这种情况下重载方法会引发错误?
问题描述
我尝试实现的简单重载示例,但出现错误。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;
但我仍然不明白为什么要这样做。任何解释将不胜感激!
解决方案
推荐阅读
- javascript - 在加载时反应渲染,但在异步调用完成时不更新
- javascript - 我可以直接从 HTML 将 HTML 元素传递给 oninput 属性中定义的函数吗?
- python - 在python中for循环期间使用.pause的代码n次
- r - R从文本中删除停用词而不将数据标记和转换为列表
- .net - 如何在 Windows 应用程序打包项目的 MSIX 文件中包含生成的应用程序清单
- javascript - 如何通过嵌套在对象数组属性中的对象属性的值来查找对象数组中的多个索引?
- javascript - javascript中的函数仅适用于其中一行
- http - 在 AngleSharp.Io 中使用代理和标头
- javascript - 期望一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:
- swift - 如果存在类型不匹配错误,是否可以将变量解码为 nil