F# Interop with Javascript in Fable: The Complete Guide

Enviroment Setup

Skip this section if you already know how to setup a minimal Fable app.

mkdir FableInterop
cd FableInterop
dotnet new -i Fable.Template::*
npm install
dotnet restore

Working with the code

The [<Emit>] Attribute

Defining the undefined

You have to be careful to always write the correct types because otherwise the code will just fail during runtime and cause unexpected behavior.

Parameterized [<Emit>] with functions

Type-safe Javascript functions with Option<’t>

Writing a JQuery binding, it’s just glue.

const div = window['$']("#main")div.css("background-color", "red")
.click(function(ev) { console.log("Clicked")})

Instance-based method chaining for the JQuery binding

  • using abstract methods to only define their type signatures.
  • abstract methods without an emit attribute are compiled using the name of the method.
  • for custom-named functions such as onClick I am using [<Emit>] to fall back to the actual name, that is click . The instance itself will be the first parameter that’s why I am using $0.click($1) where $0 is the instance and $1 is the argument.
  • the css has a paramter as a tuple to correctly compile to javascript. If I used parameters such as css : string -> string -> IJQuery I would not be able to “dot through” the code and would have to use css with it’s paramters between parentheses.
  • I kept using the JQuery.select to start the “chain”.

Working with object literals

String Literal Types, only better

Using [<Pojo>] Attribute

Pojo records are only intended for type-safe interaction with javascript libraries that require a plain object (like React components). These records lack many features, like instance and static methods and have no reflection support.

Using a list of discriminated union as object literal

Creating object literals inline

Interacting with existing Javascript code

Interacting with Javascript from npm packages

Working with overloads

Curried and Uncurried Functions




Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store