Sub topic 14
Typing Tag Functions with TemplateStringsArray
This chapter assumes you can already write a plain JavaScript tag function. It also assumes you know basic TypeScript: function signatures, rest parameters, and generics. All that changes here is that the tag gets types, so the compiler can check every call site.
The Shape of the First Parameter
TypeScript ships a built-in interface for the strings array. In lib.es5.d.ts it is declared like this:
interface TemplateStringsArray extends ReadonlyArray<string> {
readonly raw: readonly string[];
}The type is readonly for two reasons. JavaScript freezes the strings array at runtime, and the compiler should stop you from writing to it. The raw property is also readonly, and it holds the uncooked parts.
Here is a typed version of a simple transforming tag:
function upper(strings: TemplateStringsArray, ...values: unknown[]): string {
return strings.reduce(
(out, str, i) => out + String(values[i - 1]).toUpperCase() + str,
);
}
const who = 'world';
upper`hello ${who}`; // 'hello WORLD'Use unknown[] instead of any[] for the values. With unknown, you have to convert each value on purpose, as String(...) does here, before you can use it.
Constraining What Can Be Interpolated
The type of the rest parameter controls which substitutions the compiler accepts. This lets a tag reject bad input at compile time:
function px(strings: TemplateStringsArray, ...values: number[]): string {
return strings.reduce((out, str, i) => out + values[i - 1] + 'px' + str);
}
px`margin: ${4} ${8}`; // 'margin: 4px 8px'
// px`margin: ${'4'}`; // Error: Argument of type 'string' is not
// // assignable to parameter of type 'number'.The checker treats a tagged template like an ordinary call. Each ${} expression is checked against the rest parameter type in order.
Typing the Return Value
A tag can return any type, and you should declare it. A query tag might look like this:
interface Query {
text: string;
values: unknown[];
}
function sql(strings: TemplateStringsArray, ...values: unknown[]): Query {
return {
text: strings.reduce((q, str, i) => q + '$' + i + str),
values,
};
}
const q = sql`SELECT * FROM users WHERE id = ${42}`;
q.text; // 'SELECT * FROM users WHERE id = $1'Generics let the return type follow the values. When the rest parameter is a generic tuple, TypeScript infers one element type per substitution:
function capture<T extends unknown[]>(
strings: TemplateStringsArray,
...values: T
): T {
return values;
}
const parts = capture`a${1}b${'x'}`; // type: [number, string]Accepting Values Other Than Template Literals
String.raw is typed to accept { raw: readonly string[] | ArrayLike<string> } as its first argument, not only TemplateStringsArray. If your tag should also be callable by hand, use the same looser type:
function joinRaw(template: { raw: readonly string[] }, ...values: unknown[]): string {
return String.raw(template, ...values);
}
joinRaw({ raw: ['a', 'b'] }, 1); // 'a1b'Where the Types Are Wrong
The table below summarizes which type to use for each part of a tag's signature.
| Part of the signature | Recommended type | Why |
|---|---|---|
| First parameter | `TemplateStringsArray` | Matches the frozen array and its `raw` |
| Values, open-ended | `...values: unknown[]` | Forces explicit conversion |
| Values, restricted | `...values: number[]` or a union | Rejects bad input at compile time |
| Values, tracked | `<T extends unknown[]>(..., ...values: T)` | Infers a tuple per call site |
| Return | An explicit type | Tags may return anything, so declare it |
Exercise
Write the signature of a TypeScript tag css that only allows string or number substitutions and returns an object { cssText: string }. What happens when you write csscolor: ${true}?
Show answer
function css(strings: TemplateStringsArray, ...values: (string | number)[]): { cssText: string }. The call csscolor: ${true} fails to compile, because an argument of type 'boolean' is not assignable to a parameter of type 'string | number'.
Exercise
A tag reads strings[0].length, and someone calls it as tag\unicode. Does TypeScript report an error, and what happens at runtime?
Show answer
TypeScript reports no error, because strings[0] is typed as string. At runtime, strings[0] is undefined, so reading .length throws a TypeError. You can avoid this by reading strings.raw[0] or by checking for undefined first.