每当我尝试转换以下代码时,都会收到错误:
TypeScript error: /Users/development/Desktop/Source/MyApp/MyApp/app/providers/register-service/register-service.ts(30,12): Error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable<string>'.
Type '{}' is not assignable to type 'string'.
然而,我的代码看不出任何(显然)错误:
getRegisteredName(): Observable<string> {
return new Observable(observer => {
let registeredName: string = localStorage.getItem('RegisteredName');
if (registeredName) {
observer.next(registeredName);
observer.complete();
}
else {
observer.error(null);
}
});
}
为什么TypeScript转换器会拒绝此函数?
答案 0 :(得分:1)
您已指定要返回的Observable类型:
Observable<string>
但是TS在这一点上并不真正知道你真正回归的是什么。您必须通过执行以下操作告诉TS编译器:
return new Observable<string>