Typescript tuple of two boolean computations as a boolean array
I tried to make a tuple of 2 booleans in my BehaviorSubject
private someBehaviorSubject: BehaviorSubject<[boolean, boolean]> = new BehaviorSubject([false, false]);
but I am getting compile error:
Type 'BehaviorSubject<boolean[]>' is not assignable to type 'BehaviorSubject<[boolean, boolean]>'
How can I create a tuple of two booleans and initialize the BehaviorSubject correctly? Seems to be of [false, false]
type boolean[]
, not tuple, where index 0 and index 1 should be booleans.
Typescript version: 2.3.3
BehaviorSubject from rxjs v 5.0.1
source to share
Tuples are currently a bit tricky to work with with TypeScript. Array literals can be casually inferred to an array type rather than a tuple, which is what happened in this case. The compiler BehaviorSubject<boolean[]>
eagerly resolved new BehaviorSubject([false, false])
the type object BehaviorSubject<boolean[]>
without checking the type of the destination variable. This is a known issue and many related issues have been posted on the issue tracker ( # 16391 , # 15656 and possibly more) and suggestions have been made to fix it ( # 10195 , # 16656 , ...).
In special cases, when the output is not executed, you just need to resort to casting:
private someBehaviorSubject = new BehaviorSubject([false, false] as [boolean, boolean]);
source to share
Update for the next version of TypeScript (maybe 3.4):
With the new syntax that will be introduced in the next version of TypeScript, we will be able to declare a so-called "const context" . This allows us to easily declare a given array as immutable (as in "cannot be changed after declaration") and thus allow the compiler to assume a "narrow" type.
Thus, we can declare:
private someBehaviorSubject = new BehaviourSubject(<const> [false, false])
// notice the <const>, alternatively we could write "[false, false] as const"
And output the correct type BehaviourSubject<[false, false]>
source to share