11

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

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't know why i didn't tried that. It was obvious.
@Baud wan't at all obvious to me, I found out by doing typeof of a concrete function.
Sorry, but why it works?
13

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

2 Comments

What would be the point of this? If you make an instance of one of these and type is as HTMLElement, the parameter becomes a: never.
@malthe that's something that changed in TS, around 4.2 or 4.3 I think. I'd workaround it now with generics, but I'd have to have a play to get something that makes sense as an update to this answer.
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.