Sometimes when using TypeScript (or Angular), you can get error saying something like Property 'x' does not exist on type 'y', or to be more precise, it can definitely look like this:

Property 'type' does not exist on type '{}'.

How to fix this?

Let's take an example, we will instantiate empty object for  new BehaviorSubject() like this and later we will use value of it for other operations:

                    user$ = new BehaviorSubject({});
....

ngOnInit(): void {
 const prepareData = {
      user: this.user$.getValue().type,
      ...
    };
}
                  

This code from above, will throw error: Property 'type' does not exist on type '{}'

There is a couple ways to fix this:

  • Declare empty object in BehaviorSubject as type :any
    user$ = new BehaviorSubject({} as any);
  • Define custom User interface and use it when declaring BehaviorSubject value. And in this case value needs to be set to null
                    export interface UserInterface {
  type: string;
}
@Component({
....
})

export class YourClassName {
  user$ = new BehaviorSubject<UserInterface>(null);
}


                  

What could also help (in some cases) is to try to get the type by calling it like this:

                    user: this.user$.getValue()["type"]
                  

instead of this:

                    user: this.user$.getValue().type
                  

 

Another cool trick is to use "as any" on getValue() method:

                    user: (this.user$.getValue() as any).type
                  

 

☮❤️