Why do you only sometimes have to import extension methods?

138 views Asked by At

Although this question is not Angular-2-specific, let's start with an example in Angular 2:

import { Http } from "@angular/http";
import "rxjs/add/operator/toPromise";

// ...

private foo() {
    return this.http.get(url).toPromise();
}

toPromise() is an extension method for the Observable<Response> returned by this.http.get(url). You can only use it if you import rxjs/add/operator/toPromise, otherwise the compiler will complain. That file toPromise.d.ts has the following content:

import { toPromise } from '../../operator/toPromise';
declare module '../../Observable' {
    interface Observable<T> {
        toPromise: typeof toPromise;
    }
}

However, for my own extension methods, no import is needed:

my-class.ts:

export class MyClass {}

my-class-extensions.ts:

import { MyClass } from "./my-class" ;

declare module "./my-class" {
    interface MyClass {
        myExtensionMethod;
    }
}
MyClass.prototype.myExtensionMethod = () => {};

(Alternatively, the last line can be removed and the file can be renamed to my-class-extensions.d.ts.)

my-consumer.ts:

import { MyClass } from "./my-class";
// No import necessary:
// import "./my-class-extensions";

// ...

foo(obj: MyClass) {
    obj.myExtensionMethod(); // Still fine!
}

So, why do you only sometimes have to import extension methods? And what can I do do make my extension methods "modular"?

1

There are 1 answers

1
Pricey On

To answer the second part of your question, this works:

// my-class.ts
export class MyClass {
    firstMethod = (): void => {
        console.log("First method")
    } 
}

// my-class.extended.ts
import { MyClass as MyClassBase } from './my-class'

class MyClassExtended extends MyClassBase {
    secondMethod = (): void => {
        console.log("Second method")
    }
}
export { MyClassExtended as MyClass }

// index.ts
import { MyClass } from './my-class.extended'

let myClassInstance = new MyClass()
myClassInstance.secondMethod()

// Outputs "Second method"