keldar keldar - 1 month ago 9x
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) {;

else {

Why is the TypeScript transpiler rejecting this function?


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


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>