Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 576
httpNick Avatar asked Jul 03 '17 17:07

httpNick


1 Answers

Tuples are currently a bit tricky to work with in TypeScript. Array literals might be accidentally inferred to an array type rather than a tuple, which is what happened in this case. The compiler has resolved new BehaviorSubject([false, false]) too eagerly to an object of type BehaviorSubject<boolean[]>, without checking the destination variable's type. This is a known concern and many related issues were posted in the issue tracker (#16391, #15656, and possibly more) and suggestions have been laid to address it (#10195, #16656, ...).

For particular cases where inference fails, you may simply have to resort to casting:

private someBehaviorSubject = new BehaviorSubject([false, false] as [boolean, boolean]);
like image 50
E_net4 stands with Ukraine Avatar answered Sep 28 '22 08:09

E_net4 stands with Ukraine