Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript overloding

Guys where is an error in this code,
I suppose, I am covering all possible situations,
compiler saying I am wrong here – function position(a: number): IPositionDefault ,
but if there is one argument I returning object that looks like IPositionDefault, no?

function position(): IPosition
function position(a: number): IPositionDefault 
function position(a: number, b: number) :IPosition
function position(a?: number, b? :number){
    if (!a && !b){
        return {x: undefined, y: undefined}
    }
    if (a && !b){ 
        return {x: a, y: undefined, default: a.toString()}
    }
    if (!a && b){
        return {x: b, y: undefined, default: b.toString()}
    }
    
    return {x: a, y: b}
}

I expected to see no error in compiler

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

All you need for error to go away to do is to define a return type of your actual function implementation.

Change:

function position(a?: number, b? :number){

To:

function position(a?: number, b? :number): IPosition | IPositionDefault {

TypeScript Playground.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading