Software developer

Developer of webapps and more since 2016

12 Apr 2020

612
Curryfication in Typescript for safe argument binding

Tags

Introduction

In this post we will focus on how to safely bind arguments to functions such as contextual filter/sort functions in Typescript.

Using bind, the unsafe way

The first way is to use bind to add arguments to array functions. Example with a filter function :


const scopePublished = (published: boolean, article: Article)  => article.published === published;

const dataset = [{published: true}, {published: false}];

const filtered = dataset.filter(scopePublished.bind(this, true));

We have a result but this is not safe :

If we forget to bind the scopePublished function (typescript won't warn you forgot to bind an argument), the argument is not injected in the function, and at runtime it will result in error.

The functional way

The functional way, using a closure or monad is to destructure the function in two or more functions, depending on the amount of contexts :


const scopePublished = (published: boolean) =>  (article: Article)  => article.published === published;

const dataset = [{published: true}, {published: false}];

const filtered = dataset.filter(scopePublished(true));

The scopePublished function returns a function with the injected "published" context value that will be used as a filter function.

If you forget to feed the function with the right amount of arguments it won't compile.