我将flowtype添加到我的一个侧面项目中,并且遇到以下代码的混淆错误。枚举FlowType对象的数字键
可正常工作(通过抛出Error):
/* @flow */
function test(
events: {
[event: number]: {
}
}
): void {
events['hi'];
}
它引发以下错误:
8: events['hi'];
^property `hi` is a string. This type is incompatible with
4: [event: number]: {
^number
然而,这不起作用:
/* @flow */
function test(
events: {
[event: number]: {
}
}
): void {
for (const event: number in events) {
}
}
它给出以下错误:
for (const event: number in events) {
^string. This type is incompatible with
for (const event: number in events) {
^number
我在想这是为什么? According to the official documentation,Flow足够聪明,可以在将对象用作地图时为对象的类型推断出精确的值。
是否因为for循环的输入认为该对象可能包含其他字符串键控项目?我如何在保持显式类型安全的同时迭代这个?
感谢您的回复,我已经更新了问题,所以我更清楚为什么要问这个问题。我意识到所有的对象都是用字符串键入的,但是当使用对象作为地图时,Flow应该足够聪明来理解显式类型(因为人们通常会这么做)。我认为这是随着枚举,考虑到迭代映射也是一种常见的做法。请参阅[文档中的此部分](https://flowtype.org/docs/objects.html#objects-as-maps)。 – dxu