Using "open interfaces" to extend HTMLElement in TypeScript
typescript
Solution
Expanding interfaces has to be done in the root level of the code. If you try to extend an interface inside of a module, code inside of that module will only seen the interface inside of that scope.
Broken Example:
interface ExpandableInterface {
memberOfFIRSTDefinition: number;
}
module MyModule {
interface ExpandableInterface {
memberOfSECONDDefinition: number;
}
class MyClass {
constructor() {
var m: ExpandableInterface = {};
m.memberOfFIRSTDefinition; // <-- It can't see this member because it's only scoped to the one inside of the module.
}
}
}
Working example:
interface ExpandableInterface {
memberOfFIRSTDefinition: number;
}
interface ExpandableInterface {
memberOfSECONDDefinition: number;
}
module MyModule {
class MyClass {
constructor() {
var m: ExpandableInterface = {};
m.memberOfFIRSTDefinition; // <-- They're both root level, it can be seen :)
}
}
}
Problem
I would like to extend the built-in class HTMLElement with additional methods. Maybe I'm going mad, but I thought the following was the official idiom: ``` interface HTMLElement { swapChildBefore(remove: HTMLElement, insert: HTMLElement, before: HTMLElement): void; } HTMLElement.prototype.swapChildBefore = function (remove: HTMLElement, insert: HTMLElement, before: HTMLElement): void { this.removeChild(remove) this.insertBefore(insert, before) } ``` At least, according to How does prototype extend on typescript?, something like this should work. However, this seems to hide all the existing methods on HTMLElement. Is that because I've declared an interface, which hides the class of the same name? But this idiom seems to work fine with Object and Array, which are also classes.