我尝试使用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]
我不确定这是否是错误(我有raised an issue),或者是否有其他方法可以断言数组的所有成员都是特定类型。