'Type 'BehaviorSubject<false>' is not assignable to type 'BehaviorSubject<boolean>'

I have this in one of my components:

public booleanSubject: BehaviorSubject<boolean> = new BehaviorSubject(false);

When I add "strictFunctionTypes": true to the tsconfig.json file I get the following error:

× Compiling TypeScript sources through NGC
ERROR: path/to/my/component.component.ts:28:10 - error TS2322: Type 'BehaviorSubject<false>' is not assignable to type 'BehaviorSubject<boolean>'.
  Types of property 'observers' are incompatible.
    Type 'Observer<false>[]' is not assignable to type 'Observer<boolean>[]'.
      Type 'Observer<false>' is not assignable to type 'Observer<boolean>'.
        Type 'boolean' is not assignable to type 'false'.

28   public booleanSubject: BehaviorSubject<boolean> = new BehaviorSubject(false);

Does anyone know the reason and how to get it not to throw the error by keeping the strictFunctionTypes flag set to true?



Solution 1:[1]

Igor Melo Telheiro answer is on point. Just to extend it a bit.

You can either declare that field with public booleanSubject = new BehaviorSubject(false); and it will automatically infer the right type BehaviorSubject<boolean>

Or you can declare the field with a type but then the assigned value must be also of that type when declared. public booleanSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

Solution 2:[2]

Normally when I create a BehaviorSubject I just assign a type to it when initializing it. Try to it like this:

public booleanSubject = new BehaviorSubject<boolean>(false);

Doing so it will initialize the BehaviorSubject type as boolean and I believe the error will go away.

Solution 3:[3]

The reason for that is that you are assigning the variable booleanSubject as a boolean, but the output for new BehaviorSubject(false) is of type false and not of type boolean.

public booleanSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

will output a BehaviorSubject<boolean> instead of BehaviorSubject<false> and fixing the typescript error.

this usually is because of TSConfig stict -> more accurately strictFunctionTypes: true

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Igor Melo Telheiro
Solution 3 Dharman