我正在尝试观察流中发生的最新事件。每个事件可以是两种类型之一,由枚举表示。但是我在以下示例中遇到编译错误:
import { BehaviorSubject } from 'rxjs/Rx';
export enum FilterAction {
RESET, UPDATE
}
export class FilterSomething {
private _filterEvent: BehaviorSubject<FilterAction> = new BehaviorSubject(FilterAction.RESET);
get filterEvent() {
return this._filterEvent.asObservable(); // <-- behave.ts(14,12): error TS2322: Type 'Observable<FilterAction>' is not assignable to type 'FilterAction'
}
set filterEvent(action: FilterAction){
this._filterEvent.next(action);
}
}
编译错误:
behave.ts(14,12): error TS2322: Type 'Observable<FilterAction>' is not assignable to type 'FilterAction'
但是,当我使用通用的 any
时它编译(和工作)。
set filterEvent(filterAction: any) {
this._filterEvent.next(filterAction);
}
我怀疑这与枚举值有关,而不是 FilterAction
的实例.
最佳答案
问题是你的 getter
的返回类型. Getter
s 和 Setter
s 应该接受并返回相同类型的参数,即 FilterAction
在你的情况下。但是你的getter
返回 Observable<FilterAction>
.只是不要使用 getter
, 更改函数的名称。然后语言服务停止显示错误。在语言规范中:
If both accessors include type annotations, the specified types must be identical.
可以查看this出。
关于javascript - RXJS Observable 枚举类型,类型 'Observable<Type>' 不可分配给类型 'Type',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44542995/