The object may be undefined when using BehaviorSubject

I have a BehaviorSubject set up as follows:

public _location: BehaviorSubject<Location | undefined> = new BehaviorSubject(undefined);
public location$: Observable<Location | undefined> = this._location.asObservable();
public get location() {
  return this._location.getValue();
}

My goal is to access the data like this:

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

However, despite my attempts, I keep getting the Typescript error message:

[ts] Object is possibly 'undefined'.

This occurs when trying to access location.coords.latitude and location.coords.longitude.

I'm confused. I've specified that the type can be either Location or undefined. I've initialized it with undefined. I've also added a check with typeof location !== 'undefined'. What am I missing here?

Answer №1

Occasionally, TypeScript seems to get overly concerned about trivial matters.

Would you be willing to attempt the following?

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

Answer №2

Not entirely clear why TypeScript is throwing that error, however, the code could use some tidying up:

If you are using rxjs above version 5, you might need to refactor the filter and map functions.

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);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with importing CSS/SASS into Vue Cli 3 Typescript within the <script> block

Recently, I created a new Vue app using TypeScript with Vue Cli 3. However, when attempting to import CSS or Sass into my TypeScript file, I encountered the following issue: import * as sassStyles from '@/assets/sass/my.module.scss'; This re ...

Additional optional class name within a TypeScript component

I am utilizing class names to apply multiple classes to a React component. Within my button, I want the option to include a class to the component if desired, but it should be optional. Unfortunately, I encountered a type error as depicted in the image li ...

Unable to invoke a function despite using a typeof type guard

function function<T>(argument: T | (() => T)) { // @ts-expect-error return typeof argument === "function" ? argument() : argument; } Despite using the typeof type guard, I'm unable to call argument, but this issue only aris ...

Angular 2: A guide to resetting dropdown and text values when changing radio button selections

When the user interface displays two radio buttons - one for YES and one for NO - and the user clicks on YES, a dropdown is shown. Conversely, if the user clicks on NO, a textbox is displayed. How can I clear the values in the dropdown and textbox when s ...

How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration: const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } Is it possible in TypeScript to retrieve the string representation of a specific member? In C#, this could be achieved with ...

What are the steps to make standard calls from the main controller?

My website has date selection functionality on all pages, where API data is displayed based on the chosen date. However, I want the selected date to be consistent across all pages. Currently, I am using the code $scope.cb(moment().subtract(29, 'days&a ...

Angular Binding issue - Unable to bind to 'ngModel' as it is not recognized as a valid property of 'input' element, despite the property being present

I have developed a component class like the one below and I am attempting to link the class fields to the template, but encountered the following error: ERROR in src/app/admin/projects/projects.component.html: 41:34 - error NG8002: Can't bind to &ap ...

Is there a convenient method for setting up and activating real-time TypeScript checking in Windows 10 using VS Code?

After successfully installing VS Code on my Windows 10 system, I decided to follow the instructions provided here. Upon completion, Node and NPM were also installed correctly. However, I noticed a gap in the setup instructions between installing TypeScrip ...

Exploring the capabilities of combining Typescript with withStyles in the latest @material-ui/core framework

I have been working on updating some old Typescript code that was using material-ui@next to now use @material-ui/core. Typescript Version: 2.8.3 @material-ui/core: 1.1.0 I created a simple component that accepts a single prop, but when I try to use it, t ...

Creating a preview of a document with client-side scripting

I have been developing a feature that requires generating a preview in a popup for various file formats including PDF, Word, and Excel. I was able to achieve this by converting the files using Aspose.Words and Aspose.Cells. Here is the code snippet: publ ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Is it possible to access the attributes of an interface in TypeScript without relying on external libraries?

Ensuring the properties of an interface align with an object that implements it is crucial for successful unit testing. If modifications are made to the interface, the unit test should fail if it is not updated with the new members. Although I attempted ...

Challenges with implementing ng2-auto-complete in Angular2

I successfully integrated the Angular 2 ng2-auto-complete component into my project by following this helpful tutorial. The code is also available on GitHub. The current challenge I am encountering involves the formatting of my data source. It is structur ...

Ways to display map results in multiple columns utilizing react

I am facing a challenge and seeking guidance on how to achieve a specific layout using React. My goal is to display results in two columns as shown below: item 1 | item 4 item 2 | item 5 item 3 | item 6 I have attempted to check the array length and dete ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

Refining Typescript type with specific error for generics

Seeking assistance to comprehend the situation: TS playground The situation involves a store with an exec method, where narrowing down the type of exec param is crucial for a sub process. However, an error seems to arise due to the store type being generi ...

Transform event binding using PrimeNG Elements and Angular

My challenge lies in dynamically binding change events within the PrimeNG TreeTable by defining functions on my columns. I've noticed that attempting to bind the change event dynamically with my columns doesn't seem to work properly inside the Tr ...

Updating the state in a different component using React and Typescript

The Stackblitz example can be found here I'm attempting to update the useState in one component from another component. Although it seems to work here, it's not functioning properly in my actual application. Here is a snippet of the app.tsx co ...

Exploring Function Type in TypeScript: Utilizing both fat arrow and object literal type

Currently delving into the world of Typescript, I came across two methods for defining function types: using a fat arrow or an object literal. Here's an example: let myAdd1: (x: number, y: number) => number = function(x: number, y: number): n ...

While utilizing Typescript, it is unable to identify changes made to a property by a

Here is a snippet of code I am working with: class A { constructor(private num: number = 1) { } private changeNum() { this.num = Math.random(); } private fn() { if(this.num == 1) { this.changeNum(); if(this.num == 0.5) { ...