TypeScript module Augmentation

心不动则不痛 提交于 2019-12-01 04:06:45

问题


I have extension for observable. It was working perfectly fine but now I've updated to angular 6 with typescript 2.7.2.

import { Observable } from 'rxjs/Observable';
import { BaseComponent } from './base-component';
import { Subscription } from 'rxjs/Subscription';
import { Subscribable } from 'rxjs';

declare module 'rxjs/Observable' {
    export interface Observable<T> {
        safeSubscribe<T>(this: Observable<T>, component: BaseComponent,
            next?: (value: T) => void, error?: (error: T) => void, complete?: () => void): Subscription;
    }
}


export function safeSubscribe<T>(this: Observable<T>, component: BaseComponent,
    next?: (value: T) => void, error?: (error: T) => void, complete?: () => void): Subscription {
    let sub = this.subscribe(next, error, complete);
    component.markForSafeDelete(sub);
    return sub;
}

Observable.prototype.safeSubscribe = safeSubscribe;

And this code is not working

  1. 'Observable' only refers to a type, but is being used as a value here.
  2. Property 'subscribe' does not exist on type 'Observable'.

https://www.typescriptlang.org/docs/handbook/declaration-merging.html


回答1:


When merging declarations, the specified module path must exactly match the path to the actual module.

With RxJS version 6, you will need to change your module declaration, as the internal structure has changed. From memory, it should be:

declare module 'rxjs/internal/Observable' {
    export interface Observable<T> {
        safeSubscribe<T>(this: Observable<T>, component: BaseComponent,
            next?: (value: T) => void, error?: (error: T) => void, complete?: () => void): Subscription;
    }
}

For an example, see one of the patching imports in rxjs-compat.



来源:https://stackoverflow.com/questions/50321926/typescript-module-augmentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!