Typescript Pipeline Operator

Write chained function calls in Typescript

Tom • Typescript & Javascript, Functional Programming, Coding Guides •

Time for a new operator

If you’re using Typescript’s functions a lot, you may have felt the desire to better write out your code when some functions are chained together. Here’s an example of what I mean by that.

const scream = (s: string) => s + "!";
const quote = (s: string) => `"${s}"`;
cosnt toUpperCase = (s: string) => s.toUpperCase();

// The first function that executes is
// 'toUpperCase', whose results is proved
// to 'scream', which in turn returns to
// 'quote', which returns the final string
//
// "HELLO WORLD!"
const text = quote(scream(toUpperCase("Hello World")));

typescriptLanguageCheck out all coding posts

The main problem is that you have to adapt your mental model of the hierarchy of function calls to Typescript’s specification. Specifically, each function takes another functions return value as input, which results in code where the original input value is placed at the right edge.

This isn’t a problem by any means. The code works just fine, and once you’ve got accustomed to a programming language’s syntax, such constructs start to feel natural.

What the pipeline operator does differently

By using the new and currently experimental pipeline operator, Typescript enables you to write such chained function calls from left to right, where the original input is now at the left edge.

const scream = (s: string) => s + "!";
const quote = (s: string) => `"${s}"`;
cosnt toUpperCase = (s: string) => s.toUpperCase();

// And here's the new sytanx, starting
// from left and movign throught the 
// call chain to the right.
// 
// It's immediately better to read and
// self explanatory, imho.
"Hello World" |> toUpperCase |> scream |> quote;

typescriptLanguageCheck out all coding posts

The proposed syntax is very beginner-friendly in my opinion, as it reads more like human language. And by avoiding the nested function calls, the code style overall is cleaner and more readable.

Step by step

As of writing, things are still in very early development. The proposed feature shouldn’t be used in any sort of production code, but only for a little side project to toy around with. For a quick start, Firefox supports the syntax natively after setting the feature flag “--enable-pipeline-operator”. There’s also a babel-plugin available.

There are still some open questions, for example how to handle async function calls in a chain of functions using the new operator. Yet this feature looks very exciting, even though it won’t bring any substantial new features. The proposed syntax looks really good and I’m eager to await the final draft by the Typescript team.

Actions

Feedback

Suggested Posts