简体   繁体   中英

Typescript: How overload function in interface

I want to extends a native javascript type in typescript. This is possible using an interface to declare extended properties. But how to declare overloaded properties ?

interface HTMLElement {
    add:(a:string)=>void; // error: add is duplicate
    add:(a:boolean)=>void;
}

HTMLElement.prototype.add = function (a):void{
    if(typeof a=="string"){

    }
    else if(typeof a=="boolean"){

    }
}

class HTMLElement2 {
    add(a:string):void; // ok
    add(a:boolean):void;
    add(a):void{
        if(typeof a=="string"){

        }
        else if(typeof a=="boolean"){

        }
    }
}

Thank you

You were close.

interface HTMLElement {
    add(a:string): void;
    add(a:boolean): void;
}

Tipp: I always look at the implementation from Microsoft in the lib.d.ts file. In this case I typed (with Visual Studio code): document.addEventListener and looked (with ctrl + left click) how Microsoft created the interface.

The accepted answer requires the implementation to include all of the overrides. You can also allow the interface to implement any of the overloads:

interface HTMLElement {
    add: 
        ((a:string) => void) |
        ((a:boolean) => void);
}

class HTMLElementBool {
    add(a:boolean):void{
        // Assume bool
    }
}

class HTMLElementString {
    add(a:string):void{
        // Assume str
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM