I have encountered an issue with my code when setting "noImplicitAny" to true.
import ...;
@Injectable()
export class HeroService {
private _cachedHeroes: Observable<Hero[]>;
private _init: boolean;
private _heroesObserver: Observer<Hero[]>;
private _heroObserver: Observer<Hero>;
heroes$: Observable<Hero[]>;
hero$: Observable<Hero>;
public _dataStore: { heroes: Hero[], hero: Hero };
constructor (private http: Http) {
this._init = true;
this._dataStore = { heroes: [], hero: {_id: null, name: null} };
this.heroes$ = new Observable((observer: any) => this._heroesObserver = observer).share();
this.hero$ = new Observable((observer: any) => this._heroObserver = observer).share();
this._baseUrl = 'http://localhost:8081/api/hero/';
}
loadHero1(id: number) {
this.hero$ = this._cachedHeroes.map(heroes => heroes.find(hero => {hero._id === id;}))
.catch(handleError)
.subscribe( data => {
this._dataStore.hero = data;
this._heroObserver.next(this._dataStore.hero);
},
error => handleError('Could not load hero.')
);
}
.......
}
When attempting to make the code type safe by enabling "noImplicitAny", I faced the following errors:
[0] services/hero.service.ts(58,7): error TS2322: Type 'Subscription' is not assignable to type 'Observable<Hero>'.
[0] Property '_isScalar' is missing in type 'Subscription'.
[1] [BS] File changed: dist\services\hero.js
[1] [BS] File changed: dist\services\common.js
[0] services/hero.service.ts(58,65): error TS2345: Argument of type '(hero: Hero) => void' is not assignable to parameter of type '(value: Hero, index: number, obj: Hero[]) => boolean'.
[0] Type 'void' is not assignable to type 'boolean'.
I need help addressing the following questions:
- How can I convert this._cachedHeroes.map().subscribe() from type Subscription to type Observable in order to resolve the TS2322 error? Attempts like
have proven unsuccessful.<Observable<Hero[]>>.this._cachedHeroes....
- What is the correct way to define the type for the argument of the TypeScript arrow function to resolve the TS2345 error? Simply using
did not work.heroes.find( (hero: Hero) => {hero._id === id;})
In the code snippet below, how can I replace explicit usage of any with an Observer type?
this.hero$ = new Observable((observer: any) => this._heroObserver = observer).share();
Your guidance and suggestions are greatly appreciated.