【发布时间】:2017-02-16 13:52:38
【问题描述】:
我有如下所示的操作数据:
type IHasShow =
abstract member show:bool
type ShowHideNotCompletedData = {show:bool}
type ShowHideCompletedData = {show:bool}
[<Pojo>]
type ActionData =
| ShowHideNotCompleted of ShowHideNotCompletedData
| ShowHideCompleted of ShowHideCompletedData
稍后我尝试将 ShowHideNotCompletedData 或 ShowHideCompletedData 传递给函数,该函数只关心布尔“显示”成员,但无法弄清楚如何传递/转换它:
let setShowItem (data:IHasShow) negate item =
if data.show && (negate item.completed) then
{ item with show = true}
else if (negate item.completed) then
{ item with show = false}
else
item
但是如何调用这个函数呢?
let setShowFn = setShowItem (data :> IHasShow) not
错误:
Type constraint mismatch. The type
'ShowHideNotCompletedData'
is not compatible with type
'IHasShow'
试过
let setShowFn = setShowItem data not
错误:
The type 'ShowHideNotCompletedData' is not compatible with the type 'IHasShow'
除了使用 ShowHideNotCompletedData 和 ShowHideCompleted 复制粘贴 setShowItem 之外,还有其他方法吗?
如果有帮助的话;完整的源代码在这里:https://github.com/amsterdamharu/riot_redux_fable
最简单的解决方案是不传递数据而只传递布尔值:
let setShowItem show negate item =
if (negate item.completed) then//simplified if statement
{ item with show = show}
else
item
//...
| ShowHideCompleted data ->
let setShowFn = setShowItem data.show id
{ state with
showCompleted = data.show
items = state.items
|> Array.map setShowFn}
我仍然想知道如何定义泛型类型并传递它。
【问题讨论】:
标签: f#