F# 代码不够通用(使用静态成员约束)



我正在尝试创建一个通用函数,该函数检查记录的格式是否有效,前提是该记录实现了静态成员有效。当尝试在 Bolero(Blazor) 框架内的 ElmishComponent 中使用它时,我收到以下错误

此代码不够通用。当 ^childModel : (静态成员有效: ^childModel -> bool) 时,类型变量 ^childModel 无法泛化,因为它会逃脱其范围

使用以下代码

module Modal =
    type Message<'childModel, 'childMessage> = | Confirm of 'childModel | Cancel | ChildMessage of 'childMessage
    type Model<'T> = { Display : bool; Title : string; Child : 'T }
    let inline valid (x: ^t) =
        (^t: (static member valid: ^t -> bool) (x))
    type Component<'T, ^childModel, 'childMessage when 'T :> ElmishComponent< ^childModel, 'childMessage> and ^childModel : (static member valid: ^childModel -> bool)>() =
        inherit ElmishComponent<Model<'childModel>, Message<'childModel, 'childMessage>>()
        // Error is highlighted on this line
        override this.View model dispatch = 
            cond model.Display <| function
            | true ->
                div [ attr.style (if model.Display then "background: lightblue;" else "background: grey;") ] [
                    h3 [] [ text model.Title ]
                    ecomp<'T,_,_> model.Child (dispatch << ChildMessage)
                    p [] []
                    button [ 
                        // This is where I use the valid function
                        attr.disabled (if valid model.Child then null else "true")
                        on.click (fun _ -> dispatch <| Confirm model.Child)
                    ] [ text "Confirm" ]
                    button [ on.click (fun _ -> dispatch Cancel) ] [ text "Cancel" ]
                ]
            | false ->
                empty

我可能错过了一些东西,但在我看来,更简单的方法是使用子模型实现的接口 - 那么你根本不需要为静态成员约束而烦恼:

type IValidable =
  abstract IsValid : bool
type Component<'T, 'childModel, 'childMessage when 
      'T :> ElmishComponent< 'childModel, 'childMessage> and 
      'childModel :> IValidable>() =
    inherit ElmishComponent<Model<'childModel>, Message<'childModel, 'childMessage>>()
    override this.View model dispatch = 
        let test = model.Child.IsValid            
        ()

最新更新