I want to write a function with a signature int -> 'TEnumthat will throw an exception if the target enum does not contain an input value. Here is my first attempt:
let parseEnum<'TEnum when 'TEnum : enum<int>> (value : int) : 'TEnum =
let enumType = typeof<'TEnum>
if not <| Enum.IsDefined (enumType, value) then
raise <| ArgumentException (sprintf "Invalid value of %A: %d" enumType value)
enum value
The compiler shows me the following error message: "error FS0001: parameter of the declared type" TEnum "cannot be used here, because the type parameter cannot be resolved at compile time" (I think because of a function enumthat has an additional restriction).
Okay, okay, I understand the problem. I will use a statically permitted type parameter . Here is my second attempt:
let inline parseEnum2 (value : int) : ^TEnum =
let enumType = typeof<^TEnum>
if not <| Enum.IsDefined (enumType, value) then
raise <| ArgumentException (sprintf "Invalid value of %A: %d" enumType value)
enum value
: " FS3156: → " typeof<^TEnum>.
? ?