Reputation: 23
function overloading
I wrote the 2 interfaces. Also I wrote 3 overloading functions. And I have implementation of functions. And here an error - This overload signature is not compatible with its implementation signature
interface MyPosition {
x: number | undefined
y: number | undefined
}
interface MyPositionWithDefault extends MyPosition {
default: string
}
function position(): MyPosition
function position(a: number): MyPositionWithDefault // Here`s an
//error
function position(a: number, b: number): MyPosition
function position(a?: number, b?: number) {
if (!a && !b) {
return {x: undefined, u: undefined}
}
if (a && !b) {
return {x: a, y: undefined, default: a.toString}
}
return {x: a, y: b}
}
Upvotes: 2
Views: 60
Reputation: 23652
0
so using !a
seems wrong, use type narrowing.as MyPositionWithDefault
, this is more clear where this type is returned.MyPosition
once, no need in !a && !b
function position(a?: number, b?: number) {
if(typeof a === 'number' && b === undefined){
return {x: a, y: undefined, default: a.toString()} as MyPositionWithDefault;
}
return {x:a, y:b};
}
Upvotes: 1
Reputation: 22029
The compiler for some reason cannot infer the correct return type, simply adding the annotation fixes the problem:
interface MyPosition {
x: number | undefined
y: number | undefined
}
interface MyPositionWithDefault extends MyPosition {
default: string
}
function position(): MyPosition
function position(a: number): MyPositionWithDefault // No error
function position(a: number, b: number): MyPosition
function position(a?: number, b?: number): MyPosition | MyPositionWithDefault { // added return type annotation
if (!a && !b) {
return {x: undefined, y: undefined}
}
if (a && !b) {
return {x: a, y: undefined, default: a.toString() }
}
return {x: a, y: b}
}
I also cleaned up some typos.
Upvotes: 2