Sub topic 14
Typing Tag Functions with TemplateStringsArray
This chapter assumes you have written tag functions in plain JavaScript, as in earlier chapters, and that you know basic TypeScript: function signatures, generics, union types, and readonly arrays. All examples compile with strict enabled.
TypeScript treats a tagged template as a function call. The compiler checks the tag's first parameter against the strings array, checks each substitution against the remaining parameters, and gives the expression the tag's return type. Once you know how that mapping works, typing a tag uses the same tools as typing any other function.
The TemplateStringsArray Interface
The standard library (lib.es5.d.ts) declares the type of the first argument like this:
interface TemplateStringsArray extends ReadonlyArray<string> {
readonly raw: readonly string[];
}The declaration reflects two runtime facts covered earlier in this tutorial:
- The array is frozen, so it is a
ReadonlyArray<string>. You cannot callpushor assign to an index. - It has an extra
rawproperty that holds the uncooked strings, which is also read-only.
Here is the basic shape of a typed tag:
function upper(strings: TemplateStringsArray, ...values: unknown[]): string {
return strings.reduce(
(out, str, i) => out + String(values[i - 1]).toUpperCase() + str,
);
}
const who = 'world';
console.log(upper`hello ${who}`); // 'hello WORLD'unknown[] is the honest default for the values. Substitutions can be any expression, and unknown makes you convert or narrow a value before you use it. Here String(...) does the conversion. If you used any[] instead, you could call .toUpperCase() on a number without a compile error and only find out at runtime.
The Compiler Checks Substitutions Against Your Parameters
The rest parameter is a real parameter type. If you narrow it, TypeScript rejects substitutions that don't fit. This is the main reason to type a tag carefully, because it turns a convention into a compile-time rule.
type SqlValue = string | number | boolean | null | Date;
interface Query {
text: string;
values: SqlValue[];
}
function sql(strings: TemplateStringsArray, ...values: SqlValue[]): Query {
return {
text: strings.reduce((query, str, i) => query + '$' + i + str),
values,
};
}
const id = 42;
const status = 'active';
const q = sql`SELECT * FROM users WHERE id = ${id} AND status = ${status}`;
console.log(q.text); // 'SELECT * FROM users WHERE id = $1 AND status = $2'
console.log(q.values); // [42, 'active']
// const bad = sql`SELECT * FROM t WHERE x = ${{ nested: true }}`;
// Error: Argument of type '{ nested: boolean; }' is not assignable
// to parameter of type 'SqlValue'.The return type is Query, not string, and q gets that type. Nothing in the type system assumes a tag returns a string.
You can also use a tuple for the rest parameter when each position needs its own type:
function pair(strings: TemplateStringsArray, ...values: [string, number]): string {
const [label, amount] = values;
return `${strings[0]}${label.toUpperCase()}${strings[1]}${amount.toFixed(2)}${strings[2]}`;
}
console.log(pair`Item ${'tea'} costs ${3}.`); // 'Item TEA costs 3.00.'
// pair`Item ${3} costs ${'tea'}.`; // Error: number is not assignable to string
// pair`Only ${'one'}`; // Error: expected 3 arguments, but got 2The arity error is worth noticing. TypeScript counts the substitutions and compares that count with the tuple length, so a template with the wrong number of ${} slots fails to compile.
Generic Tags and Inferred Return Types
Generics work as they do in ordinary calls. TypeScript infers type parameters from the substitutions:
function collect<T extends unknown[]>(
strings: TemplateStringsArray,
...values: T
): { parts: readonly string[]; values: T } {
return { parts: strings, values };
}
const result = collect`a ${1} b ${'two'} c ${true}`;
// result.values has type [number, string, boolean]
console.log(result.values); // [1, 'two', true]A tag can also take a type argument directly. The syntax puts the type arguments between the tag and the backtick:
function parse<T>(strings: TemplateStringsArray, ...values: unknown[]): T {
return JSON.parse(String.raw(strings, ...values)) as T;
}
interface Point { x: number; y: number }
const p = parse<Point>`{"x": ${1}, "y": ${2}}`;
console.log(p.x + p.y); // 3The as T assertion is a promise you make to the compiler, and nothing checks it at runtime. Libraries that use this pattern, such as typed GraphQL helpers, usually generate T from a schema so that the promise is backed by something.
Branded Return Types for Safe Output
The HTML-escaping tag from an earlier chapter returns a plain string. Code that receives a string can't tell whether it was escaped. A branded type makes the type record that difference:
type SafeHTML = string & { readonly __brand: 'SafeHTML' };
const escapeHTML = (value: unknown): string => String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
function html(strings: TemplateStringsArray, ...values: unknown[]): SafeHTML {
const out = strings.reduce((acc, str, i) => acc + escapeHTML(values[i - 1]) + str);
return out as SafeHTML;
}
function render(target: { innerHTML: string }, content: SafeHTML): void {
target.innerHTML = content;
}
const box = { innerHTML: '' };
const user = '<img src=x onerror=alert(1)>';
render(box, html`<p>Hello, ${user}!</p>`); // OK
// render(box, `<p>Hello, ${user}!</p>`); // Error: string is not assignable to SafeHTML
console.log(box.innerHTML); // '<p>Hello, <img src=x onerror=alert(1)>!</p>'The brand exists only at compile time. At runtime the value is an ordinary string, so the brand adds no cost.
Typing this for Member Tags
When the tag is a method, you can declare this as a fake first parameter. TypeScript removes it from the call signature, and the strings array is still the first real argument.
interface Formatter {
prefix: string;
tag(this: Formatter, strings: TemplateStringsArray, ...values: unknown[]): string;
}
const formatter: Formatter = {
prefix: '[log] ',
tag(strings, ...values) {
return this.prefix + String.raw(strings, ...values);
},
};
console.log(formatter.tag`count=${3}`); // '[log] count=3'
const detached = formatter.tag;
// detached`count=${3}`;
// Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Formatter'.The detached call fails at runtime in JavaScript as well. TypeScript reports it at compile time instead.
Calling a Tag Without Template Syntax
Sometimes you need to call a tag as a normal function, for example in a test or when the parts come from somewhere else. A plain string[] will not type-check, because it has no raw property:
function upper(strings: TemplateStringsArray, ...values: unknown[]): string {
return strings.reduce(
(out, str, i) => out + String(values[i - 1]).toUpperCase() + str,
);
}
// upper(['hello ', ''], 'world');
// Error: Property 'raw' is missing in type 'string[]'
function makeStrings(cooked: string[], raw: string[] = cooked): TemplateStringsArray {
return Object.freeze(Object.assign([...cooked], { raw: Object.freeze([...raw]) }));
}
console.log(upper(makeStrings(['hello ', '']), 'world')); // 'hello WORLD'A hand-built array has no call-site identity. If a tag caches by strings, as lit does, each makeStrings call creates a new cache entry. Build such arrays once and reuse them.
If your tag never reads raw, you can accept a looser type such as readonly string[]. Template syntax still type-checks, because TemplateStringsArray is assignable to readonly string[]. The standard library declares String.raw with a structural parameter, { raw: readonly string[] | ArrayLike<string> }, which is why String.raw({ raw: ['a', 'b', 'c'] }, 1, 2) compiles.
Gotchas
| Issue | What happens | What to do |
|---|---|---|
| Literal text is not typed | `strings` is `readonly string[]`, so TypeScript does not know the actual text of the parts | Validate the text at runtime, or generate types with a build step |
| Cooked strings can be `undefined` | A tagged template with an invalid escape such as `\unicode` gives `undefined` at runtime, but the type says `string` | Read `strings.raw[i]` when you accept arbitrary escapes, or check for `undefined` |
| Template literal types are a separate feature | `` type Id = `user-${number}` `` is a type-level string pattern and has nothing to do with tag functions | Don't search for tag-typing help under "template literal types" |
| `any[]` values | Turns off checking for every substitution | Use `unknown[]`, a union, or a tuple |
| Optional chaining | `` obj?.tag`x` `` is a syntax error | Check that the tag exists first |
Exercise
You declare function money(strings: TemplateStringsArray, ...values: number[]): string. Which of these lines compile: (a) moneyTotal: ${9.5}, (b) moneyTotal: ${'9.5'}, (c) moneyNo values here?
Show answer
Lines (a) and (c) compile. Line (b) fails because the substitution '9.5' is a string, which is not assignable to number. Line (c) compiles because a rest parameter accepts zero values, so the call is money(strings) with an empty values array.
Exercise
A test calls html(['<b>', '</b>'], name), where html takes a TemplateStringsArray, and gets a compile error. Why, and what is the smallest change that fixes it without any type assertion?
Show answer
A plain string[] has no raw property, so it does not satisfy TemplateStringsArray. Pass an array that has one, such as Object.assign(['<b>', '</b>'], { raw: ['<b>', '</b>'] }), or call the tag with template syntax: html<b>${name}</b>. If the tag never reads raw, you could instead widen its parameter to readonly string[].
Exercise
Why does the type of strings[0] say string even though it can be undefined at runtime, and in what situation does that happen?
Show answer
TemplateStringsArray extends ReadonlyArray<string>, so the cooked entries are typed as string. Since ES2018, a tagged template that contains an invalid escape sequence such as \unicode or \xZZ gets undefined for that cooked string, while strings.raw keeps the original text. The type does not model that case, so a tag that must accept arbitrary escapes should read strings.raw or check for undefined.