How to get type of the module in F#

You could add a marker type to the module and then discover the module's type from that:

module Foo =  
    type internal Marker = interface end
    let t = typeof<Marker>.DeclaringType

It would certainly be nice to have a moduleof operator... Since there's not one, the easiest way to do what you want is probably to use the Metadata library in the F# PowerPack:

#r "FSharp.PowerPack.Metadata.dll" 
open Microsoft.FSharp.Metadata

// get .NET assembly by filename or other means
let asm = ...

let fasm = FSharpAssembly.FromAssembly asm
let t = fasm.GetEntity("Foo").ReflectionType

Unfortunately, this won't work with dynamic assemblies (such as those generated via F# Interactive). You can do something similar using vanilla System.Reflection calls, but that's more dependent on having a good understanding of the compiled form that your module takes.


It can also be done using Quotations. First, define this helper function somewhere:

open Microsoft.FSharp.Quotations.Patterns

let getModuleType = function
| PropertyGet (_, propertyInfo, _) -> propertyInfo.DeclaringType
| _ -> failwith "Expression is no property."

Then, you can define a module and get its type like this:

module SomeName =
    let rec private moduleType = getModuleType <@ moduleType @>

Hope this helps.