Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 493
Baud Avatar asked May 20 '16 18:05

Baud


1 Answers

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.

like image 196
Philipp Endrulat Avatar answered Sep 24 '22 01:09

Philipp Endrulat