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"?
To answer the second part of your question, this works: