如何断言所有$ ReadOnlyArray成员都属于某种类型?

时间:2018-11-13 16:42:56

标签: javascript flowtype

我尝试使用for..of迭代数组,并在类型不匹配时引发异常:

type FooPacketType = 'foo';
type BarPacketType = 'bar';

type PacketType =
  FooPacketType |
  BarPacketType;

const packets: $ReadOnlyArray<PacketType> = [];

function ingestFooPackets(fooPackets: $ReadOnlyArray<FooPacketType>) {}

for (const packet of packets) {
  if (packet !== 'foo') {
    throw new Error('Unexpected state');
  }
}

ingestFooPackets(packets);

这给出了一个错误:

18: ingestFooPackets(packets);
                     ^ Cannot call `ingestFooPackets` with `packets` bound to `fooPackets` because string literal `bar` [1] is incompatible with string literal `foo` [2] in array element.
References:
8: const packets: $ReadOnlyArray<PacketType> = [];
                                 ^ [1]
10: function ingestFooPackets(fooPackets: $ReadOnlyArray<FooPacketType>) {}
                                                         ^ [2]

https://flow.org/try/#0C4TwDgpgBAYg9nACgQwMYGsLACrmgXigHIAzBIgbgChRIoAhZAJxQy1zsKICNnKqaeKK0w4h+KlFgIR7IQB9JDZrLGRqVVHAB2AZ2BQwaUboBcUACQAlCMgAmAeW0AbEAEEmTZCAA8qjhAAfFCEANoAuhokAK7aqMAAljpQCdoA5hD68EjGWLoAFGQ5bMBmljb2Tq4eXr7Z-niBAJRQAN4AvgJkTFD5WnoGRiVQcCSGuaUtrUoJY-lDolAAhPhcRURTSlLAABZMcADuUNoQRwCinnBM+UQAqicAHpDxEHZQ+sjAEBvUUp2dVFSGSyMgmBQWeSaFCAA

我不确定这是否是错误(我有raised an issue),或者是否有其他方法可以断言数组的所有成员都是特定类型。

0 个答案:

没有答案