Hacklang: 不能 return 来自 (function(...): KeyedIterable<arraykey, mixed>) 的向量

Hacklang: Cannot return Vector from (function(...): KeyedIterable<arraykey, mixed>)

我有一个方法可能 return Map 或 Vector,并且由于这两种类型都实现了 KeyedIterableVector<T> 具体实现了 KeyedIterable<int, T> — 我想我可以用 KeyedIterable<arraykey, T> return 类型涵盖这两种情况。但是,即使 arraykey 是比 int 更通用的类型,这也不起作用。例如,类型检查器抱怨以下代码:

<?hh // strict
class A {
   public static function foo(): KeyedIterable<arraykey, mixed> {
      return Vector{};
      /*
      Invalid return type (Typing[4110])
      This is an array key (int/string)
      It is incompatible with an int
      Considering that this type argument is invariant with respect to KeyedIterable
      */
   }
}

为什么我不能这样做?

这是因为 KeyedIterable 不是只读的,所以不能采用子类型。

例如,A::foo()->toMap() 将具有类型签名中的类型 Map<arraykey, mixed>,但实际类型为 Map<int, mixed>.