I am facing an issue with function overloading in a scenario where a function can either return something or undefined, depending on the input parameter possibly being undefined as well.
Here is an example:
type Point = { x: number; y:number}
function symetry(point : Point) : Point;
function symetry(point : undefined ) : undefined;
function symetry(point : Point | undefined) : Point | undefined {
if(!point) return undefined;
return {
x : -point.x,
y : -point.y
}
}
const p1 : Point = symetry({x: 10, y:-4});
const someFunc = (v : number): Point | undefined => {
if(v%2 === 0) return undefined;
return { x:v,y:v}
}
const p2 = symetry(someFunc(0));
const p3 = symetry(someFunc(1));
This code will not compile and shows the following error message for both p2 =
and p3 =
invocations:
No overload matches this call.
Overload 1 of 2, '(point: Point): Point', gave the following error.
Argument of type 'Point | undefined' is not assignable to parameter of type 'Point'.
Type 'undefined' is not assignable to type 'Point'.
Overload 2 of 2, '(point: undefined): undefined', gave the following error.
Argument of type 'Point | undefined' is not assignable to parameter of type 'undefined'.
Type 'Point' is not assignable to type 'undefined'.
How can I resolve this issue?
Link to TypeScript Playground