Typed Tagged Templates: interpolation on steroids for javascript

Timothée Clain
Le Wagon
Published in
3 min readDec 28, 2018

Hi there! Today I’d like to talk about one of my beloved modern JavaScript feature: Tagged Templates.

Tagged What?

Basically Tagged Templates are an extension of the basic interpolation mechanism that you normally uses in ES6+.

Using backticks you can elegantly insert values in a string (multi line by the way, :-))

In one word?

By using the backticks notation with a function identifier, you basically have a template engine for free.

An example please!

Don’t worry, it’s actually less scary than it sounds.

Let’s take a function like

We’ll see the actual arguments later.

I can now call the function with this syntax:

Weird isn’t it?

There’s more: I can actually pass interpolations with the familiar ${} syntax.

Let’s try it:

I have access to computed values from the surrounding scope of my function call !

This syntax is an actual function call of myTemplate.

So what’s the magic actually?

Let’s see the arguments passed to the function:

  • The first argument is a list of invariant strings
  • the n others arguments are all the other interpolation produced by ${} usage.

For instance, if I make this call:

The *first argument* will be a list of all string segments that don’t change in my passed interpolation:

Of course, if you don’t use any interpolations, you will have a single element inside this array, the entire string.

The next argument will be my first interpolation, in this case, it is a constant string: Timothee.

So if we have n interpolation in our template string, we all have n+1 elements in our first array, and n more arguments passed to the function.

Cool, but how is it useful?

Whenever you need to apply transformations to a string with interpolation (aka dynamic values), this proves to be very useful.

For instance, one could build a template engine respecting the native semantics of es6 and provide this kind of public API:

Actually, this already exists: https://lit-html.polymer-project.org/

In the ReactJS world, this technique is used to generate pre-styled components from CSS code for CSS-in-js solutions as emotion or styled-components.

How can we type tagged templates ?

In you are using typescript, you can add type information to our tagged templates:

The idea is to type the first argument as the TemplateStringsArray type and the subsequent interpolations to whatever you need.

Let’s take an example. Let’s say you want to have auto-completable access to your theme from a styled-component:

And you got auto-completion + type-safety of your theme keys for free!

That’s it for today. Till next time !

Originally published at https://dev.to on December 28, 2018.

--

--

Timothée Clain
Le Wagon
Writer for

A dreamer, musician and software engineer. I currently craft delightful Javascript Experiences (React) for @pyx4.