TypeScript: Cannot overload interface method with different return types
Bug Report
Defining an overloaded method in an interface raises an error during implementation if overloads have different return types.
π Search Terms
overload, method, interface, factory function
π Version & Regression Information
Doesnβt work in v3, v4 or v5.
β― Playground Link
Playground link with relevant code
π» Code
interface Shape {
area(x: number): number;
area(x: number, y: number): string;
}
π Actual behavior
class ShapeImpl implements Shape {
// β
area(_x: number, _y?: number): number | string {
return 0;
}
}
function createShape(): Shape {
return {
// β
area(_x: number, _y?: number): number | string {
return 0;
},
};
}
π Expected behavior
class ShapeImpl implements Shape {
// β
area(_x: number, _y?: number): number | string {
return 0;
}
}
function createShape(): Shape {
return {
// β
area(_x: number, _y?: number): number | string {
return 0;
},
};
}
More details
If the return type does not change, overloads work as expected.
β
interface Shape {
area(x: number): number;
area(x: number, y: number): number; // π
}
class ShapeImpl implements Shape {
area(_x: number, _y?: number): number {
return 0;
}
}
function createShape(): Shape {
return {
area(_x: number, _y?: number): number {
return 0;
},
};
}
Also works if the overloads are defined in the class or on root level functions
β
class Shape {
area(x: number): number;
area(x: number, y: number): string;
area(_x: number, _y?: number): number | string {
return 0;
}
}
function area(x: number): number;
function area(x: number, y: number): string;
function area(_x: number, _y?: number): number | string {
return 0;
}
About this issue
- Original URL
- State: closed
- Created a year ago
- Reactions: 14
- Comments: 17 (8 by maintainers)
Ok, but, whats the difference here?
^ playground link
^ playground link
Essentially #47669 (focuses on arrow functions but itβs the same issue: we currently have no way to say βcheck this the same loose way that overload implementation are checkedβ)
implementsclauses donβt change the shape of your class; this fact is intentional. IOW, for these two snippetsand
ShapeImpl.areahas the same type in both.