keldar keldar - 2 months ago 29
TypeScript Question

Typing a returned observable

Whenever I try to transpile the following code, I receive the error:

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'.


Yet I cannot see anything (obviously) wrong with my code:

getRegisteredName(): Observable<string> {
return new Observable(observer => {
let registeredName: string = localStorage.getItem('RegisteredName');

if (registeredName) {
observer.next(registeredName);

observer.complete();
}
else {
observer.error(null);
}
});
}


Why is the TypeScript transpiler rejecting this function?

Answer

You have specified the type of Observable you are going to return:

Observable<string>

but the TS doesn't really know at this point what are you really returning. You have to tell it to TS compiler by doing:

return new Observable<string>
Comments