TypeScript不允许使用函数作为观察者回调

时间:2016-10-27 14:50:07

标签: typescript

我有以下工作的TypeScript代码和测试:

menu.service.ts

import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';

export class MenuService {
  private events = new Subject();

  public subscribe(next): Subscription {
    return this.events.subscribe(next);
  }

  public next(event?): void {
    this.events.next(event);
  }
}

menu.service.spec.ts

import { MenuService } from './menu.service';

describe('MenuService', () => {
  let menuService: MenuService;

  beforeEach(() => {
    menuService = new MenuService();
  });

  it('should call a subscriber when an event is fired', function() {
    const subscriber = jasmine.createSpy('subscriber');
    menuService.subscribe(subscriber);
    menuService.next();
    expect(subscriber).toHaveBeenCalled();
  });
});

我现在正试图强制执行更好的文档和编码标准。其中一部分是添加类型。所以我改变了服务:

import { Observer } from 'rxjs/Observer';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';

export class MenuService {
  private events = new Subject();

  /**
   * Subscribe to events when the menu opens.
   *
   * @param next The callback for the subscription.
   * @returns The subscription for the event.
   */
  public subscribe(next: Observer<null>): Subscription {
    return this.events.subscribe(next);
  }

  public next(event?): void {
    this.events.next(event);
  }
}

但是,现在打字稿不再允许我通过间谍了。我尝试接受Function,但是对this.events.subscribe进行了类型检查会引发类型错误。

我该如何解决这个问题?

修改

确切的错误是:

Argument of type 'Spy' is not assignable to parameter of type 'Observer<null>'. at line 14 col 31
  Property 'next' is missing in type 'Spy'.

2 个答案:

答案 0 :(得分:0)

Subject类型是通用的,但您没有为其指定约束 尝试这样的事情:

export class MenuService {
  private events = new Subject<string>();

  /**
   * Subscribe to events when the menu opens.
   *
   * @param next The callback for the subscription.
   * @returns The subscription for the event.
   */
  public subscribe(next: Observer<string>): Subscription {
    return this.events.subscribe(next);
  }

  public next(event?: string): void {
    this.events.next(event);
  }
}

您应该将string的使用替换为您正在使用的实际类型。

修改

我不确定这个Spy对象是什么,但是如果你确定它可以通过那么:

const subscriber = jasmine.createSpy('subscriber') as (event: string) => void;

答案 1 :(得分:0)

如果导入错误的Observable,您可能会收到next() missing的奇怪错误。

我遇到了一些奇怪的错误,我错误地导入了以下内容(!)

import { Observable } from '@aspnet/signalr-client/dist/src/Observable';

这个签名为.subscribe(Observer<T>),但当我切换到使用时,这变为subscribe(observer?: PartialObserver<T>)

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';