Skip to main content

fsharp-nullness-interop

Handle F# nullness checking (Nullable enable, FS3261, FS3262 in F# 9 and later) at .NET interop boundaries, and fix FS0041 "A unique overload could not be determined" from new BCL overloads such as TimeSpan.FromSeconds(int64). Covers BCL members that return `| null`, correct null handling with match and Option.ofObj, null leaks that the compiler does not report, and when suppression is acceptable. Use when an F# build reports FS3261, FS3262, or FS0041, when the user turns on nullness checks or TreatWarningsAsErrors, or when F# code calls .NET APIs that can return null.

v1.0.0New

Unsigned, install at your own risk

Unverified

This skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.

Install this skill

No account required. Pick your tool, or use the command that detects it for you.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install fsharp-skills-fsharp-nullness-interop
Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/fsharp-skills-fsharp-nullness-interop/SKILL.md

Setup guide →
0Save

Instructions

F# nullness at interop boundaries

F# nullness checking makes .NET reference types that can be null visible as T | null.
The compiler reports most problems. The risk is the wrong fix: a fix that compiles and
hides a real null. Convert each T | null to an F# type once, at the boundary. Then the
rest of the code uses T or T option.

scripts/run.ps1 verifies the null results and diagnostics below. Verify
lists the rules that it does not verify.

Turn on the checks

<PropertyGroup>
  <Nullable>enable</Nullable>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

<Nullable>enable</Nullable> passes --checknulls+. Nullness diagnostics are warnings
(FS3261, FS3262). TreatWarningsAsErrors makes them fail the build.

Members that return | null

These members return T | null. Using the result as T gives FS3261.

MemberNull when
JsonElement.GetString()the JSON value is null
JsonSerializer.Deserialize<T>the document is null, also for F# records
Uri.TryCreate(s, kind) out valuethe parse fails, so it is typed Uri | null even on true
Environment.GetEnvironmentVariablethe variable is not set
exn.InnerExceptionthere is no inner exception
Path.GetDirectoryNamethe path is a root, such as C:\ or /. A bare file name gives "", not null.
TextReader.ReadLine(), Console.ReadLine()end of input
obj.ToString(), Type.FullNamethe API allows null

Handle null at the boundary

NeedUse
Value or fallbackmatch x with | null -> fallback | v -> v
Null and empty both mean "none"match x with | null | "" -> None | v -> Some v
optionx |> Option.ofObj
Resultmatch x with | null -> Error "..." | v -> Ok v
Out value of a Try method| true, NonNull u -> ...
Two named casesmatch x with | Null -> ... | NonNull v -> ...
let tryHost (s: string) : string option =
    match Uri.TryCreate(s, UriKind.Absolute) with
    | true, NonNull u -> Some u.Host
    | _ -> None

let rec rootMessage (ex: exn) : string =
    match ex.InnerException with
    | null -> ex.Message
    | inner -> rootMessage inner

Rules that the build does not tell you in advance:

  • isNull x and String.IsNullOrEmpty x do not narrow string | null to string. The
    else branch still gives FS3261. Use match.
  • Do not mix | null -> with | NonNull v ->. After | null, the value is already
    non-null. NonNull then gives FS3262 and the match gives FS0025. Use | v ->, or use
    Null and NonNull together.
  • Annotate public return types. Without an annotation, the compiler infers T | null
    and moves the null to the caller.
  • A string binding cannot hold null. let mutable x: string = null gives FS3261.
    Declare string | null, or better, use string option.
  • Passing ex.InnerException to a parameter of type exn gives FS3261 with the text
    The types 'exn' and 'exn | null' do not have compatible nullability. Match on the
    value before the call, or declare the parameter as exn | null and match inside.

Null leaks that compile clean

The compiler does not report these. Each one compiles with nullness and
TreatWarningsAsErrors on.

CodeResult for null
Some(reader.ReadLine()) with no type annotationSome null, not None. The type becomes (string | null) option.
string x on string | null"". A missing value becomes an empty string.
nonNull xthrows NullReferenceException
Unchecked.nonNull xpasses the null on. It fails later, far from the cause.
#nowarn "3261", <NoWarn>FS3261</NoWarn>hides every later null in the file or project

Use Option.ofObj instead of Some on a .NET result. Use string x only when an empty
string is the correct value for null.

When suppression is acceptable

Use nonNull or Unchecked.nonNull only when the API cannot return null in this call,
and the type does not say so. Write the reason in a comment on the same line or the line
above. Example: a value that a Try method returned with true, when you cannot use
NonNull in the pattern. Never suppress FS3261 for a file or a project to get a build
to pass.
NonNullQuick and nullArgCheck throw on null like nonNull. They need the same written reason.

// GetEntryAssembly is null only in unmanaged hosts. This exe always has one.
let entry = Unchecked.nonNull (Assembly.GetEntryAssembly())

New BCL overloads (FS0041)

.NET 9 added int64 overloads to TimeSpan.FromSeconds, FromMinutes,
FromMilliseconds, and FromMicroseconds. An int argument used to convert to float.
Now it matches no overload exactly, so the compiler reports FS0041. FromHours and
FromDays have int overloads and still compile.

CodeFix
TimeSpan.FromSeconds 5TimeSpan.FromSeconds 5.0
TimeSpan.FromSeconds(pown 2 n)TimeSpan.FromSeconds(float (pown 2 n))
let toSpan x = TimeSpan.FromSeconds xlet toSpan (x: float) = TimeSpan.FromSeconds x

Convert the argument at the call. Do not change the type of a public parameter or a
record field to fix FS0041. For other FS0041 errors, read the candidate list in the
message and annotate the argument with one candidate type.

Verify

  1. Build with Nullable and TreatWarningsAsErrors on. Do not add NoWarn for 3261.
  2. Search the changed code for nonNull, #nowarn, Some, and string used as a function
    (string x, x |> string). Check each use on a .NET result against the tables above.
  3. Run the code with null inputs at each boundary: a JSON null, an unset environment
    variable, an exception with no inner exception, and an empty reader.

To check the facts in this skill, run the bundled proof:

pwsh ./scripts/run.ps1

The runner builds scripts/Clean with nullness and warnings as errors,
runs it, and compares 19 results. It then builds each file in scripts/breaks
and checks that it fails with only the diagnostic codes in its // expect: lines and with the message text in its // expect-text: lines.
The clean lines it prints are the results in the tables above.

These rules come from the F# compiler documentation and are not bundled proofs:
<Nullable>enable</Nullable> passes --checknulls+, #nowarn "3261" and NoWarn
hide later nullness warnings, and an unannotated function infers T | null from its body.

This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
fsharp-performance-typesChoose F# collections and types for run time and allocation, and prove the result with a measurement. Use when F# code is slow or allocates too much, when a reviewer asks for fewer passes or allocations, or when you write a hot loop over list, array, seq, Map, Set, Dictionary, option, tuple, or sprintf.0 installsoptimize-fsharp-typecheck-graphOptimize an F# project's graph-based type-checking critical path with measured compiler evidence. Use when an F# build spends substantial time in type checking, a `.graph.md` file shows excessive file dependencies, shared namespaces or auto-open modules serialize checking, signature files may unblock parallel work, or a compile-performance refactor needs source- and binary-compatibility validation.0 installsfsharp-signature-filesAdd F# signature files (.fsi) that expose only the API that callers use, and hide type representations so callers must use constructor functions. Covers generating a starting point with --allsigs or --sig, removing helpers from the .fsi, abstract types, attribute and interface mismatches (FS3888, FS0050, FS1200), signature errors (FS0034, FS0193, FS0238), XML docs, InternalsVisibleTo for tests, and a public-surface check of the built assembly. Use when the user asks for signature files, a smaller public API, encapsulation of an F# library, or hidden constructors.0 installsfsharp-native-aotMake F# code work under .NET Native AOT (PublishAot) and find the failures that publish warnings do not show. Covers which printf, sprintf, failwithf, and interpolated-string forms work, silent data loss from %A and ToString on unions and tuples, logging, System.Text.Json for F# records, option, list, and unions, configuration binding, warnings-as-errors, and JIT-versus-native verification. Use when an F# project sets PublishAot or PublishTrimmed, when the user asks about F# AOT or trimming, when F# output or logs differ in a native build, or when F# JSON fails with "Reflection-based serialization has been disabled".0 installsfsharp-failure-pathsMake failures in F# code explicit instead of crashing or hiding them. Use when writing or reviewing F# that calls partial functions (List.head, Seq.find, Map.find, .Value), uses failwith, falls back with defaultArg or Option.defaultValue, catches exceptions, or combines several validations into one Result.0 installsparse-dont-validatePreserve invariants in types when changing domain models, input boundaries, or state transitions.0 installs

More from F# Skills

View source →
fsharp-env-capabilitiesPass dependencies in F# as one generic env value whose capabilities are small IProvideX interfaces, so the compiler infers each function's dependency set and tests build only what a function needs. Also binds IConfiguration settings to F# types, validates them with Result at startup, and exposes the validated type as a capability instead of IOptions<T>. Use when an F# function list of dependency parameters grows, when wiring IServiceProvider or ASP.NET Core DI into F# functions, when binding or validating appsettings.json or IOptions settings in F#, when a test must substitute one dependency, or when the user says env, capability, IProvide, or environment pattern.0 installsfsharp-iwsam-errorsDesign F# error types as IWSAM leaves (interfaces with static abstract members) so each function declares only its own errors and the caller picks one edge type. Use when adding or composing Result error types across F# functions, when a nested error DU needs Result.mapError at every call, when a new error case must reach every handler, or when the user says IWSAM, error tree, or edge type.0 installsfsharp-library-api-designDesign and change the public API of an F# library without breaking its consumers. Covers F#-specific breaking changes (new union cases, new record fields, curried and tupled forms, generic and inline functions, RequireQualifiedAccess, renamed modules), binary breaks that a clean build does not show (a new optional parameter, a wider parameter type, cross-assembly inlining of a small function body into Release consumers, --nooptimizationdata), safe extension patterns (overloads, new functions), a C#-friendly surface, SemVer for each change type, the lowest FSharp.Core version, and compatibility checks with package validation and old consumers. Use when the user adds to or changes a published F# library, asks whether a change is breaking, picks a version number, or exposes F# code to C#.0 installsfsharp-serializationSerialize F# records, unions, options, and maps to JSON that matches a wire contract, and keep old JSON readable. Use when writing or reviewing F# code that calls System.Text.Json, configures FSharp.SystemTextJson (JsonFSharpConverter, JsonFSharpOptions), writes Thoth.Json encoders or decoders, adds a DTO layer, reads JSON from another service, or adds or renames a union case or record field that is stored or sent as JSON.0 installsfsharp-verify-apiCheck the real signature of a .NET or F# API before F# code uses it, so the build does not loop on FS0039, FS0001, FS0074, or FS0078. Use when writing F# against a NuGet package, a package version that changed its API, an unfamiliar type, or an .fsx script with0 installsfsharp-binary-compatibilityChange a published F# library so that apps compiled against the old version still run against the new DLL with no rebuild. Covers new parameters on let-bound functions (no overloads), optional member parameters, inferred type changes, union case order and new cases, record fields, inline and [<Literal>] values, cross-assembly inlining (--nooptimizationdata), renames with CompiledName, curried and tupled parameters, abstract interface members, the FSharp.Core dependency, and automated checks with package validation, apicompat, and an F# signature diff. Use when the user changes the public API of an F# library or NuGet package in a minor or patch release, asks for a non-breaking change, or asks whether an F# change is binary compatible.0 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.635 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.535 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.346 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.246 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.173 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions145 installs

Frequently asked questions about fsharp-nullness-interop

What does the fsharp-nullness-interop skill do?

Handle F# nullness checking (Nullable enable, FS3261, FS3262 in F# 9 and later) at .NET interop boundaries, and fix FS0041 "A unique overload could not be determined" from new BCL overloads such as TimeSpan.FromSeconds(int64). Covers BCL members that return `| null`, correct null handling with match and Option.ofObj, null leaks that the compiler does not report, and when suppression is acceptable. Use when an F# build reports FS3261, FS3262, or FS0041, when the user turns on nullness checks or TreatWarningsAsErrors, or when F# code calls .NET APIs that can return null. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the fsharp-nullness-interop skill?

Run `npx @skills-hub-ai/cli install fsharp-skills-fsharp-nullness-interop` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/fsharp-skills-fsharp-nullness-interop/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does fsharp-nullness-interop work with?

fsharp-nullness-interop runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the fsharp-nullness-interop skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use fsharp-nullness-interop after installing it?

In Claude Code, type `/fsharp-skills-fsharp-nullness-interop` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the fsharp-nullness-interop skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.