Welcome! We notice you're using an outdated browser, which will result in a degraded experience on this site. Please consider a modern, fully supported browser.

webbureaucrat

The articles are just window-dressing for code snippets I want to keep.

ReasonML Journey Part III: Generics, Promises, and ExtendableEvent.waitUntil()

This post continues the quest of trying to recreate the JavaScript service worker class ExtendableEvent in ReasonML. In this post I will show how to extend the subtype of event to include ExtendableEvent's waitUntil method, which takes a generic Promise as a parameter.

The BuckleScript official documentation gives us a good starting point for defining functions that reference JavaScript object methods, as shown below:

[@bs.send] external getElementById: (document, string) => Dom.element 
    = "getElementById";

In this example, [@bs.send] external tells BuckleScript to call out to JavaScript, trusting that there is such a function as the string "getElementById". The rest of the statement provides the types we will use to interact with it. We need to adapt this to take a type parameter for our promise.

[@bs.send] external waitUntil: (extendableEvent, Js.Promise.t('a)) => unit
    = "waitUntil";

This gives us access to the JavaScript function "waitUntil", which takes our extendableEvent as a first "parameter" (in this context) and a strongly typed promise, returning unit, which, in functional languages, is like void.

This doesn't quite do what we need though--we need this method of ExtendableEvent to be heritable. We can do this by using our supertype.

[@bs.send] 
external waitUntil: (extendableEvent_like('subtype), Js.Promise.t('a)) => unit
    = "waitUntil";

This allows waitUntil to accept any subtype of extendableEvent_like, not just extendableEvent itself.

And we're done for the day. In the next post, I'll work on the npm side of things so that we can use our new type elsewhere.

I write to learn, so I welcome your constructive criticism. Report issues on GitLab.

← Home