Search code examples
powershellf#recorddiscriminated-union

How to use F# records or discriminated unions in PowerShell?


I created a F# project by running these commands:

dotnet new sln -o DotnetCoreProj
cd DotnetCoreProj
dotnet new classlib -lang 'F#' -o src/MyFSModule
dotnet sln add src/MyFSModule/MyFSModule.fsproj
cd src/MyFSModule
@'
namespace MyFSModule
module jwt = 
    type jwtHeader = {
      typ: string
      alg: string
    }

    type hsAlgorithm = HS256 | HS384 | HS512
'@ | Out-File Library.fs -Encoding UTF8
dotnet build
dotnet publish
Import-Module ./bin/Debug/net6.0/publish/MyFSModule.dll

Even though I import the module, I am unable to use the types.

PS> $test = [MyFSModule]
InvalidOperation: Unable to find type [MyFSModule].
PS> $test = [MyFSModule]::new()
InvalidOperation: Unable to find type [MyFSModule].
PS> $test = [jwt]              
InvalidOperation: Unable to find type [jwt].
PS> $test = [jwt]::new()
InvalidOperation: Unable to find type [jwt].
PS> $test = [MyFSModule+jwt]::new()
InvalidOperation: Unable to find type [MyFSModule+jwt].
PS> $test = [MyFSModule+jwt]       
InvalidOperation: Unable to find type [MyFSModule+jwt].
PS> $test = [MyFSModule+hsAlgorithm]
InvalidOperation: Unable to find type [MyFSModule+hsAlgorithm].
PS> $test = [hsAlgorithm]           
InvalidOperation: Unable to find type [hsAlgorithm].
PS> $test = [jwt+hsAlgorithm]
InvalidOperation: Unable to find type [jwt+hsAlgorithm].
PS> $fs = [MyFSModule.jwt]
InvalidOperation: Unable to find type [MyFSModule.jwt].

When I run Get-Module -Name MyFSModule, nothing is exported either.

How do I make F# types available in PowerShell?


Solution

  • You were almost right.

    C:\Projects\psfspoc> [MyFSModule.jwt+jwtHeader]::new("typ","alg")
    
    typ  alg
    ---  ---
    typ  alg
    
    C:\Projects\psfspoc> [MyFSModule.jwt+hsAlgorithm]::HS256
    
    Tag IsHS256 IsHS384 IsHS512
    --- ------- ------- -------
      0    True   False   False
    

    It's quite nice to explore the options by start writing [MyFSModule.jwt+ and then use ctrl-space to select the right option.

    It's btw a very nice idea to use F# types from Powershell.