2017-04-07 59 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 
}