8

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

Baud
  • 182
  • 1
  • 1
  • 8

2 Answers2

19

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.

11

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
    }
}
Keith
  • 150,284
  • 78
  • 298
  • 434