为什么有时只需要导入扩展方法?

时间:2016-12-14 11:44:24

标签: typescript typescript2.1

虽然这个问题不是Angular-2特有的,但让我们从Angular 2中的一个例子开始:

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

// ...

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

toPromise()Observable<Response>返回的this.http.get(url)的扩展方法。如果导入rxjs/add/operator/toPromise,则只能使用它,否则编译器会抱怨。该文件toPromise.d.ts包含以下内容:

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

但是,对于我自己的扩展方法,不需要导入:

MY-class.ts:

export class MyClass {}

我的级-extensions.ts:

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

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

(或者,可以移除最后一行,并且可以将文件重命名为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!
}

那么,为什么有时只需要导入扩展方法?我能做些什么才能使我的扩展方法“模块化”?

1 个答案:

答案 0 :(得分:0)

要回答问题的第二部分,这有效:

// 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"