两个布尔值的打字稿元组被推断为布尔类型的数组

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

我尝试制作一个包含两个布尔值的元组以放入我的 BehaviorSubject

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

但我收到一个编译错误:

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

如何创建两个布尔值的元组,并正确初始化 BehaviorSubject?似乎认为 [false, false] 是类型 boolean[] 而不是索引 0 和索引 1 必须是布尔值的元组。

打字稿版本:2.3.3

来自 rxjs v 的 BehaviorSubject5.0.1

目前在 TypeScript 中使用元组有点棘手。数组文字可能会被意外地推断为数组类型而不是元组,这就是本例中发生的情况。编译器已将 new BehaviorSubject([false, false]) 过于急切地解析为类型 BehaviorSubject<boolean[]> 的对象,而没有检查目标变量的类型。这是一个已知问题,许多相关问题已发布在问题跟踪器中 (#16391, #15656, and possibly more) and suggestions have been laid to address it (#10195, #16656, ...)。

对于推理失败的特定情况,您可能只需要求助于转换:

private someBehaviorSubject = new BehaviorSubject([false, false] as [boolean, boolean]);

TypeScript 3.4 更新:

随着 TypeScript 3.4 中引入的新语法,我们将可以选择声明所谓的 "const context"。这使我们可以轻松地将给定的数组声明为不可变的(如 "cannot be changed after declaration"),从而允许编译器采用 "narrow" 类型。

这样我们可以声明:

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

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

并推断出正确的类型BehaviourSubject<[false, false]>