Typescript tuple of two booleans being inferred as an array of type boolean

Viewed 1599

I tried making a tuple of two booleans to place in my BehaviorSubject

private someBehaviorSubject: BehaviorSubject<[boolean, boolean]> = new BehaviorSubject([false, false]);

but I get a compilation error saying:

Type 'BehaviorSubject<boolean[]>' is not assignable to type 'BehaviorSubject<[boolean, boolean]>'

How can I create a tuple of two booleans, and initialize the BehaviorSubject properly? It seems to think [false, false] is of type boolean[] and not a tuple where index 0, and index 1 are required to be booleans.

Typescript version: 2.3.3

BehaviorSubject from rxjs v5.0.1

2 Answers

Update for TypeScript 3.4:

With a new syntax being introduced in TypeScript 3.4, we'll have the option 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.

This way we can declare:

private someBehaviorSubject = new BehaviourSubject(<const> [false, false])

// notice the <const>, alternatively we could write "[false, false] as const"

And infer the correct type BehaviourSubject<[false, false]>

Related