Functional Programming in TypeScript

Aaron Dilley
Jan 26 · 2 min read

Functional programming with the help of utility libraries like Ramda or Lodash can make composing certain functions a breeze. A trivial example in JavaScript:

One of the knocks against functional programming — and JavaScript in general — is that despite its declarative centering, composing functions in this manner removes any input-output signature from the method and relies on thorough documentation, semantically relevant naming conventions, and devs who invest time into both.

Enter TypeScript: the self-documenting type guard and validator JavaScript pre-compiler. TypeScript is offered as a rejoinder to functional programming because the need for declarative flows seems to matter less if we can describe and guarantee the inputs and outputs of a given function.

It’s true that TypeScript does add these checks and regardless of whether or not you use functional programming, the move to TypeScript is well worth investing in it. But TypeScript and FP are not mutually exclusive.

To see how let’s look at function interfaces in TypeScript. Consider our getName function from above. We might want to restrict the input to a User data object and extract the name value. We could write this as

With a function interface this becomes

Of course this by itself seems even more verbose than the original. But for a whole class of similar methods it saves space while adding consistency. For example:

By revisiting our first composition we see we can use this interface yet again:

Admittedly UserStringAttrFunc isn't the most concise name but you get the idea.

A common task is getting an existing type, mutating it (or a copy of it) in some way and returning the mutated type. This can be thought of as a T → T transformation, an isomorphism of sorts.

In TypeScript we can describe this with mapped types:

With this mapped type we can now describe our composed mutator functions with ease.

One bit of icing on the cake for those using VS Code — hovering over functions defined with this mapped type wrapper will automatically fill in the specified type:

Front End Developer and Crossword Enthusiast

More From Medium

More from Aaron Dilley

More from Aaron Dilley

Argument Zero

52

Also tagged JavaScript

Also tagged Functional Programming

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade