2017-04-07 54 views
2

对于RemoteEntity每一个实例不兼容的,我得到的类型参数This type is incompatible with empty一个错误,在newRemoteEntity引用为valuenull值:也许型泛型类型参数是空

export type RemoteEntity<T: Identifiable> = { 
    value: ?T; 
    error: ?Error; 
    // ... 
} 

export function newRemoteEntity(): RemoteEntity<*> { 
    return { 
    value: null, // error 
    error: null, // OK 
    // ... 
    } 
} 

如果我不是声明value: ?Object,这些错误消失(但随后我得到与我的类型绑定的损失有关的其他错误)。我错过了什么,或者是这种FlowType错误/怪癖吗?

+0

什么是“可识别”类型? T需要是“可识别的”,但newRemoteEntity将其转换为空值。我想这是错误的根源。你能链接到flowtype.org/try的例子吗? – thejohnbackes

+0

我刚刚贴上了这个例子,并且定义了我自己的'Identifiable'类型并且没有错误。这个问题有一些缺失。 –

+0

我永远无法获得'flowtype.org/try'工作;在多个浏览器中只有三个涟漪点。 'Identifiable'只是'Type Identifiable = {id:string}'。 –

回答

1

我发现一个解决方法是将字段设置为可选的(而不是必需的,但使用maybe-type)。但是,它使得其他代码更复杂一些(因为我必须检查空值而不是将它们传播到对象文字中),所以我宁愿让may-types工作。

export type RemoteEntity<T: Identifiable> = { 
    value?: T; 
    error?: Error; 
    pendingAction: ?string; 
    // ... 
} 

export function newRemoteEntity(): RemoteEntity<*> { 
    return { 
    pendingAction: null, 
    // ... 
    } 
} 

export function requested<T: Identifiable>(
    state: RemoteEntity<T>, action: string, id?: string): RemoteEntity<T> { 
    // Maybe-type version was more concise: 
    // return { 
    // state: id && state.value && state.value.id === id ? state.value : null, 
    // error: null, 
    // pendingAction: action, 
    // // ... 
    // } 
    const result: RemoteEntity<T> = { 
    pendingAction: action, 
    // ... 
    } 
    if (id && state.value && state.value.id === id) { 
    result.value = state.value 
    } 
    return result 
}