[英]F# Type Constraint Mismatch when using a constraint on a generic function
[英]F# Code is not sufficiently generic (using a static member constraint)
我正在嘗試創建一個通用函數,用於檢查記錄是否采用有效格式,前提是記錄實現了靜態成員有效。 當嘗試在 Bolero (Blazor) 框架內的 ElmishComponent 中使用它時,我收到以下錯誤
此代碼不夠通用。 類型變量 ^childModel 當 ^childModel : (static member valid : ^childModel -> bool) 無法泛化,因為它會超出其范圍
使用以下代碼
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
()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.