Baud
Baud

Reputation: 313

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

Upvotes: 11

Views: 13157

Answers (3)

thehale
thehale

Reputation: 1756

For simple scenarios like yours, the TypeScript docs recommend defining the function parameter as a union of types.

Always prefer parameters with union types instead of overloads when possible

For example,

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

Upvotes: 0

Keith
Keith

Reputation: 155662

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
    }
}

Upvotes: 13

Philipp Endrulat
Philipp Endrulat

Reputation: 216

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.

Upvotes: 20

Related Questions