Search code examples
genericsf#type-extension

F# type extension of generic type with concrete type parameter


Is it possible to make a type extension for a generic type with a concrete type parameter? I failed with these syntaxes:

Syntax 1:

type Foo<Bar> with

    member this.BarStuff = // access `Bar´ specifics

Syntax 2:

type Foo<'T when 'T :> Bar> with

   member this.BarStuff = // access `Bar´ specifics

Solution

  • Yes, you can but you should use the C# style syntax:

    open System.Runtime.CompilerServices
    
    type Bar = Bar
    type Foo<'t> = Foo of 't
    
    [<Extension;Sealed>]
    type Extensions =
        [<Extension>]
        static member BarStuff (this: Foo<Bar>) = ()
    
    
    let x = (Foo Bar).BarStuff