2016-12-15 71 views
0

我将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循环的输入认为该对象可能包含其他字符串键控项目?我如何在保持显式类型安全的同时迭代这个?

回答

0

这与Flow无关,的确如此。 Javascript中的对象只能有字符串和符号属性。当您使用方括号访问属性时,其他所有内容都会隐式转换为字符串。当你使用for inObject.keys,虽然你总是会得到字符串。

+0

感谢您的回复,我已经更新了问题,所以我更清楚为什么要问这个问题。我意识到所有的对象都是用字符串键入的,但是当使用对象作为地图时,Flow应该足够聪明来理解显式类型(因为人们通常会这么做)。我认为这是随着枚举,考虑到迭代映射也是一种常见的做法。请参阅[文档中的此部分](https://flowtype.org/docs/objects.html#objects-as-maps)。 – dxu

-1

我在搜索答案时遇到了this thread,这可能表明目前存在仅用于类型的for-in循环处理的错误。