I'm trying to make a BehaviorSubject that will accept only values of the AvailableLanguages enum, but the compiler doesn't agree with my code for some reason. Can you tell me why?
I'm using Angular 12.2.10.
Here is the service:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
export enum AvailableLanguages {
EN = "en-US",
IT = "it-IT"
}
@Injectable({
providedIn: 'root'
})
export class UserService {
_selectedLanguage$: BehaviorSubject<AvailableLanguages> = new BehaviorSubject(AvailableLanguages.EN);
constructor() { }
}
Here is the compiler's error:
Error: src/app/services/user.service.ts:15:3 - error TS2322: Type 'BehaviorSubject<AvailableLanguages.EN>' is not assignable to type 'BehaviorSubject<AvailableLanguages>'.
Types of property 'observers' are incompatible.
Type 'Observer<AvailableLanguages.EN>[]' is not assignable to type 'Observer<AvailableLanguages>[]'.
Type 'Observer<AvailableLanguages.EN>' is not assignable to type 'Observer<AvailableLanguages>'.
Type 'AvailableLanguages' is not assignable to type 'AvailableLanguages.EN'.
15 _selectedLanguage$: BehaviorSubject<AvailableLanguages> = new BehaviorSubject(AvailableLanguages.EN);
~~~~~~~~~~~~~~~~~~
× Failed to compile.
Hmm, probably because you are using strict
in your tsconfig.json
?
Not an issue as per se, though. You just need to make sure your types are "aligned".
So, your declaration:
_selectedLanguage$: BehaviorSubject<AvailableLanguages> = new BehaviorSubject(AvailableLanguages.EN);
Should be:
_selectedLanguage$: BehaviorSubject<AvailableLanguages> = new BehaviorSubject<AvailableLanguages>(AvailableLanguages.EN);
Or simply let TSC to infer the proper type:
_selectedLanguage$ = new BehaviorSubject<AvailableLanguages>(AvailableLanguages.EN);