citykid
citykid

Reputation: 11070

How can I extend a build class, like HTMLElement or Node, inside a typescript module?

This code work in a typescript file:

interface Node {
    replaceWith(newnode): void;
}

Node.prototype.replaceWith = function(newnode: Node) {
    this.parentElement.replaceChild(newnode, this);
};

It stops working as soon as the file becomes a module. So by adding this:

export let x = 42 // export statement turns the ts file into a module

the compiler complains: Property 'replaceWith' does not exist on type 'Node'. Why is this and how to work around?

I understand that the extension must be declared in the global "scope" and the module is no longer global enough. But while in C++ for instance I can always add brackets around a block and make it global scope, in typescript I do not see a similar way.

Upvotes: 0

Views: 71

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249786

Global types must be declared in global if you are in a module, otherwise they will be considered just a regular module scoped type:

declare global {
    interface Node {
        replaceWith(newnode: Node): void;
    }    
}
Node.prototype.replaceWith = function(newnode: Node) {
    this.parentElement.replaceChild(newnode, this);
};

Upvotes: 1

Related Questions