Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

Object is possibly 'undefined' with BehaviourSubject

I have a BehaviourSubject like:

public _position: BehaviorSubject<Position | undefined> = new BehaviorSubject(undefined);
public position$: Observable<Position | undefined> = this._position.asObservable();
public get position() {
  return this._position.getValue();
}

which I am trying to use like so:

this.position$.subscribe((position) => {
  if (typeof position !== 'undefined') {
    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  }
});

but no matter what I try, I continue to see the Typescript error:

[ts] Object is possibly 'undefined'.

for position.coords.latitude and position.coords.longitude.

I don't understand. I've specified that the type can be either Position or undefined. I've given it an initial undefined value. I've also guarded the variable with typeof position !== 'undefined'. What's going on?

Upvotes: 0

Views: 575

Answers (2)

sabithpocker
sabithpocker

Reputation: 15558

Not exactly sure why typescript is showing that error, but the code can be made cleaner:

If you use rxjs > 5 you may have to rewrite the filter and map

public _position: BehaviorSubject<Position> = new BehaviorSubject(null);
public position$: Observable<Position> = this._position.asObservable();
public get position() {
  return this._position.getValue();
}

this.position$
    .filter(Boolean)
    .map(position => position.coords)
    .subscribe((coords) => {
        let latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
});

Upvotes: 1

Josh Stevens
Josh Stevens

Reputation: 4221

TypeScript sometimes gets its knickers in a twist over nothing..

can you try

this.position$.subscribe((position) => {
  if (position && position.coords) {
    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  }
});

Upvotes: 1

Related Questions