Two string parameters, and nothing to check them
In this project access to the browser's storage goes through a dedicated service, and for a good
reason: the keys follow a convention, fc:v1:domain:identifier, with a prefix and a
version number that serve to delete all the application's data in one go without touching that of
others. The examples written in the service's documentation are fc:v1:auth:user and
fc:v1:gamification:profile_abc123.
The method that composes them has this signature:
get<T>(domain: string, id: string, fallback: T). The domain is any string at all.
So gamifications instead of gamification compiles. Auth with a
capital letter compiles too. And the failure they produce is not an error: it is a read that returns
the fallback value, forever, because the key written is not the one read. Data that is not saved and
signals nothing.
The number of domains in an application is small and known. What is missing is not the knowledge, it
is a way of communicating it to the compiler. Template literal types, added in TypeScript 4.1, do
exactly this: they let you describe the shape of a string instead of accepting any
string. This is the last article of the series, and it uses the union of literal strings that
article 05 taught you to derive from
the catalog. The errors reported are those of TypeScript 7.0.2, the latest version on
the npm registry on 2026-11-13, tried with strict on; with 5.9.3 the texts are the same.
A key described as a rule, not as an example
// An example convention: fc:v1:<domain>:<id>
export type Dominio = 'auth' | 'gamification' | 'preferences';
export type ChiaveStorage = `fc:v1:${Dominio}:${string}`;
export function componiChiave(dominio: Dominio, id: string): ChiaveStorage {
return `fc:v1:${dominio}:${id}`;
}
export function dominioDi(chiave: ChiaveStorage): Dominio {
// split returns string[]: the third piece must be reasserted.
const pezzi = chiave.split(':');
return pezzi[2] as Dominio;
}
const k = componiChiave('gamification', 'profile_abc123');
console.log(k);
console.log(dominioDi(k));
console.log(dominioDi('fc:v1:auth:user:with:other:colons'));
// An empty id is a string, and the template accepts it.
export const vuota: ChiaveStorage = 'fc:v1:auth:';
// Output of tsc 7.0.2: no errors.
// Output of node 24.11.0:
// fc:v1:gamification:profile_abc123
// gamification
// auth
The central line is type ChiaveStorage = `fc:v1:${Dominio}:${string}`,
and it must be read as a template: a string that starts with the literal prefix, continues with one
of the allowed domains, a colon, and then any text. Three things about this syntax are the ones you
will use, and each has a consequence if you get it wrong: the backticks, types (not values) inside the interpolation, and distribution over unions. The Node output also shows that
dominioDi works with an identifier that contains other colons, and that
'fc:v1:auth:', with an empty identifier, is a valid key for the type, because the empty
string is a string.
The backticks are mandatory and are not an aesthetic detail: with plain quotes that would be a
single literal string, that is the type that contains exactly the text
fc:v1:${Dominio}:${string} with the dollar sign inside. It is an error
that produces no useful message, because the resulting type is valid and simply never matches
anything. You can see it with a perfectly valid key:
type Dominio = 'auth' | 'gamification' | 'preferences';
// Plain quotes: it is not a template, it is a literal string with the symbols inside.
type ChiaveSbagliata = 'fc:v1:${Dominio}:${string}';
// A perfectly valid key is not assignable.
export const k: ChiaveSbagliata = 'fc:v1:auth:user';
// Output of tsc 7.0.2:
// 03-apici.ts(7,14): error TS2322: Type '"fc:v1:auth:user"' is not assignable to type '"fc:v1:${Dominio}:${string}"'.
The compiler rejects 'fc:v1:auth:user' and in the message reprints the expected type with
the braces and the dollar, "fc:v1:${Dominio}:${string}" between double
quotes: it is the sign that the template was not interpreted. If you see a message like that, check
the backticks.
Inside the interpolation go types, not values. I tried the main ones, and the consequences are in the output:
type ConString = `event:${string}`;
type ConAny = `event:${any}`;
type ConBoolean = `active:${boolean}`;
type ConNumber = `page-${number}`;
type ConBigint = `count:${bigint}`;
// These compile: same set of texts for string and for any.
export const a: ConString = 'event:anything';
export const b: ConAny = 'event:anything';
export const c: ConNumber = 'page-12';
export const d: ConBigint = 'count:12';
// These do not: any does not remove the prefix, number and bigint demand digits.
export const e: ConAny = 'other:x';
export const f: ConNumber = 'page-twelve';
export const g: ConBigint = 'count:1.5';
// boolean expands into two literal strings: a probe says so.
export const sonda: never = null as unknown as ConBoolean;
// Output of tsc 7.0.2:
// 08-interpolazioni.ts(14,14): error TS2322: Type '"other:x"' is not assignable to type '`event:${any}`'.
// 08-interpolazioni.ts(15,14): error TS2322: Type '"page-twelve"' is not assignable to type '`page-${number}`'.
// 08-interpolazioni.ts(16,14): error TS2322: Type '"count:1.5"' is not assignable to type '`count:${bigint}`'.
// 08-interpolazioni.ts(19,14): error TS2322: Type '"active:false" | "active:true"' is not assignable to type 'never'.
// Type '"active:false"' is not assignable to type 'never'.
With string and with any the template accepts the same set of texts, but the
prefix stays: 'other:x' is rejected (line 14). number and
bigint demand that the text be a number of that type: 'page-twelve' and
'count:1.5' do not pass. boolean, which is already a union of two values,
expands into "active:false" | "active:true". And this is the point from which the
interesting part starts: when you interpolate a union the compiler distributes, and
the type becomes the union of all the possible combinations. The Handbook puts it this way: for each
interpolated position the unions are multiplied together. You can see it in the error message further
down.
The componiChiave function is the practical reason why all this is not an exercise. Its
return type is ChiaveStorage, and the compiler checks that the interpolated template
satisfies it: it is not a cast, it is a check. I test it by changing the prefix in the body, and by
passing a domain that is any string:
type Dominio = 'auth' | 'gamification' | 'preferences';
type ChiaveStorage = `fc:v1:${Dominio}:${string}`;
// The prefix in the body does not match the return type.
export function componiVecchia(dominio: Dominio, id: string): ChiaveStorage {
return `fc:v2:${dominio}:${id}`;
}
// A domain that arrives as a plain string is not enough.
export function componiLarga(dominio: string, id: string): ChiaveStorage {
return `fc:v1:${dominio}:${id}`;
}
// Output of tsc 7.0.2:
// 04-prefisso-nel-corpo.ts(6,3): error TS2322: Type '`fc:v2:auth:${string}` | `fc:v2:gamification:${string}` | `fc:v2:preferences:${string}`' is not assignable to type '`fc:v1:auth:${string}` | `fc:v1:gamification:${string}` | `fc:v1:preferences:${string}`'.
// Type '`fc:v2:auth:${string}`' is not assignable to type '`fc:v1:auth:${string}` | `fc:v1:gamification:${string}` | `fc:v1:preferences:${string}`'.
// 04-prefisso-nel-corpo.ts(11,3): error TS2322: Type '`fc:v1:${string}:${string}`' is not assignable to type '`fc:v1:auth:${string}` | `fc:v1:gamification:${string}` | `fc:v1:preferences:${string}`'.
Neither function compiles. The first, because fc:v2: does not match the prefix of the
type, and the compiler lists the three alternatives with the wrong prefix. The second, because
dominio: string produces fc:v1:${string}:${string}, a
type wider than the one expected: to get the guarantee, the parameter must be the Dominio
type, not string. It is the point where the convention stops being a comment and becomes
something the compiler enforces.
The compiler's message, which explains the mechanism
These are the real errors on a badly written domain, on an old version of the prefix and on a domain with a capital letter:
type Dominio = 'auth' | 'gamification' | 'preferences';
type ChiaveStorage = `fc:v1:${Dominio}:${string}`;
// 'gamifications' is not in the union: the key is not assignable.
export const chiave: ChiaveStorage = 'fc:v1:gamifications:profile';
// The wrong version of the prefix is rejected too.
export const chiaveVecchia: ChiaveStorage = 'fc:v0:auth:user';
// With a capital letter in the domain: same fate.
export const maiuscola: ChiaveStorage = 'fc:v1:Auth:user';
// Output of tsc 7.0.2:
// 02-errori.ts(5,14): error TS2322: Type '"fc:v1:gamifications:profile"' is not assignable to type '`fc:v1:auth:${string}` | `fc:v1:gamification:${string}` | `fc:v1:preferences:${string}`'.
// 02-errori.ts(8,14): error TS2322: Type '"fc:v0:auth:user"' is not assignable to type '`fc:v1:auth:${string}` | `fc:v1:gamification:${string}` | `fc:v1:preferences:${string}`'.
// 02-errori.ts(11,14): error TS2322: Type '"fc:v1:Auth:user"' is not assignable to type '`fc:v1:auth:${string}` | `fc:v1:gamification:${string}` | `fc:v1:preferences:${string}`'.
The expected type that the compiler prints is not the template I wrote: it is the union of three templates, one per domain. It is the distribution described above, made visible. The practical consequence is worth noting: the precision of this check depends on how small the union is. Three domains give three templates and a readable message; twenty domains give twenty templates and a long error message, which stays correct and is much less convenient. Then there is a hard limit, which can be measured:
type Cifra = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
type DaZeroAOtto = Exclude<Cifra, '9'>;
// 9 x 10^4 = 90,000 combinations: the compiler copes.
export type Novantamila = `${DaZeroAOtto}${Cifra}${Cifra}${Cifra}${Cifra}`;
export const a: Novantamila = '00000';
// 10^5 = 100,000 combinations: the compiler gives up.
export type Centomila = `${Cifra}${Cifra}${Cifra}${Cifra}${Cifra}`;
export const b: Centomila = '00000';
// Output of tsc 7.0.2:
// 06-limite.ts(9,25): error TS2590: Expression produces a union type that is too complex to represent.
The product of unions is accepted up to 90,000 combinations and rejected at 100,000, with the TS2590 error, "Expression produces a union type that is too complex to represent". I cannot say where the exact threshold between the two values lies: I know that 90,000 passes and 100,000 does not, with version 7.0.2 and with 5.9.3. The Handbook, in the page on template literal types, recommends ahead-of-time generation for large unions of strings, and this measurement explains why. With three domains you are far from the limit; three unions of fifty elements multiplied together give 125,000 combinations, that is more than the threshold I measured.
The point where precision is lost, and must be reasserted
The dominioDi function in the first block contains a cast, and I left it on purpose
because it is honest and instructive. The standard library's split method declares that
it returns string[], and this does not depend on the precision of the input type: the
compiler does not know that a string matching that template, split on the colons, has its third piece
in Dominio. It does not even know how many pieces result: the identifier can contain
other colons, as the output of the first block shows, and the third piece is still the domain.
Here the cast asserts something true, which can be demonstrated from the shape of the type, and
declares where the jump is. It is the category that article
01 called "a cast that declares a known hole", and the difference from a lying cast is that this
one can be verified by rereading the type. The alternative without a cast exists, and it is not a
conditional type but a run-time check: a type guard, like those of article
03, which checks the piece against the list of domains. The following file shows it, together
with the conditional type with infer that, for a key written as a literal, extracts the
domain at compile time.
export const DOMINI = ['auth', 'gamification', 'preferences'] as const;
export type Dominio = (typeof DOMINI)[number];
export type ChiaveStorage = `fc:v1:${Dominio}:${string}`;
// The run-time check replaces the cast.
function èDominio(testo: string): testo is Dominio {
return (DOMINI as readonly string[]).includes(testo);
}
export function dominioDi(chiave: ChiaveStorage): Dominio {
const candidato = chiave.split(':')[2];
if (candidato === undefined || !èDominio(candidato)) {
throw new Error(`Invalid domain in ${chiave}`);
}
return candidato;
}
// At compile time, for a literal key, the domain is extracted with infer.
export type DominioDelModello<C extends string> =
C extends `fc:v1:${infer D extends Dominio}:${string}` ? D : never;
console.log(dominioDi('fc:v1:preferences:theme'));
try {
dominioDi('fc:v1:auth:x'.replace('auth', 'other') as ChiaveStorage);
} catch (e) {
console.log((e as Error).message);
}
export const sonda: never = null as unknown as DominioDelModello<'fc:v1:auth:user'>;
// Output of tsc 7.0.2:
// 05-senza-cast.ts(29,14): error TS2322: Type '"auth"' is not assignable to type 'never'.
// Output of node 24.11.0:
// preferences
// Invalid domain in fc:v1:other:x
DOMINI is the source of truth, an as const list from which
Dominio is derived with an indexed access, the technique of article 05.
èDominio is the guard, and dominioDi uses it to return the piece without any
cast: if the piece is not a domain, it throws, as the last line of Node shows. The
DominioDelModello type is a conditional type: for a literal key such as
'fc:v1:auth:user' the probe shows that the result is "auth". The choice
between cast and guard is a compromise between lines written and guarantees, not between right and
wrong: in an application service the declared cast is enough, on a library the guard is better.
Where it pays and where it does not
The pattern gives the most when a string has a structure and a closed set of parts. These are the cases in which I use it, and they are independent of one another.
- Storage keys with a prefix and a version, that is the case of this article: a typo in the domain becomes a compile error instead of data that is not saved.
- Event names with a namespace, like
analytics:clickorform:submit, where the verb and the object come from two known lists. - Content identifiers with a language, like
articolo-itandarticolo-en, which in a two-language project prevent composing a nonexistent language code. - Names of CSS custom properties, to tie the tokens declared in the stylesheet to the names used in the code, which is a misalignment that produces no run-time error.
- Routes with a language prefix, where the initial segment belongs to a closed union and the rest is free.
Five cases, a single shape: one part of the string belongs to a set you know, and the rest is free. If you can say which part is closed and which is open, the template writes itself; if you cannot, the problem is not the type's but the convention's, which is not yet a convention.
It does not pay in two situations, and recognizing them saves time. The first is when the set of parts is open or very large: a template that interpolates a union of fifty elements produces fifty combinations, the messages become unreadable and, by multiplying several unions, you reach the compiler limit measured above. The second is when the string is composed elsewhere and arrives at the program already formed: there is nothing to check at compile time, and you need a guard that checks the shape at run time, because a type does not check data it did not see being born.
What you can do now, and what you hold at the end of the series
You can now describe the shape of a string instead of accepting any string, and you know that the
syntax wants backticks and types inside the interpolation. You know that interpolating a union
distributes the template over all the combinations, that this makes the error message precise with
three domains and cumbersome with twenty, and that beyond 100,000 combinations the compiler gives up.
You also know where the precision breaks, that is in split, which returns
string[] whatever the input type, and that you have two ways out: the declared cast or
the guard.
The series ends here, and the six articles are a single line of reasoning: how much information the
type keeps, and where it throws it away. Article
01 measures the escape routes that strict leaves open. 02
puts unknown in place of any at the point where data enters.
03 teaches the compiler a type
with a guard, and when that guard lies. 04
makes impossible states unwritable, with the exhaustiveness check.
05 checks a catalog without losing
its keys. This one, 06, describes the shape of a string. If you must start from just one, start from
your own code: look for a function that accepts two or three parameters of type string
only to concatenate them. Every time you find one, you have a place where a typo compiles.
Frequently asked questions
What is a template literal type?
A type that describes the shape of a string instead of accepting any string. It is written between backticks, with literal parts and interpolations that contain types, for example fc:v1:${Dominio}:${string}. The compiler checks that a string matches the template.
Why does my template literal type never match?
Almost always because it is written with plain quotes instead of backticks. In that case it is not a template but a single literal string that contains the characters of the interpolation, dollar and braces included: a valid type that matches nothing.
What can go inside the interpolation?
Types, not values: string, number, bigint, boolean, or a type that resolves to literal strings such as a union. When you interpolate a union the compiler distributes the template over all the combinations, which is why the error message lists one template per member.
Why does split lose the type precision?
Because the standard library declares split with return type string[], regardless of how precise the input type is. The compiler does not deduce that a string conforming to the template, split on the colons, produces a piece that belongs to the union of the domains.
When is it better to avoid this pattern?
When the set of parts is open or very large, because the combinations multiply, the error messages become unreadable and beyond 100,000 combinations the compiler gives up with TS2590. And when the string arrives already formed from outside: in that case you need a guard at run time.
Sources
- TypeScript Handbook - Template Literal Types: the multiplication of unions in every interpolated position and the recommendation to generate large unions ahead of time, read; consulted on 2026-11-13.
- TypeScript 4.1 - release notes: only the heading of the section that introduces template literal types, checked; consulted on 2026-11-13.
- Announcing TypeScript 7.0: the nature of the compiler used for the tests (native port), only the opening read; consulted on 2026-11-13.
- The errors, including TS2590 and the threshold between 90,000 and 100,000 combinations, and the outputs are produced by
tsc --noEmit --strict --noImplicitReturns --target ES2022 --module ESNext --moduleResolution bundler file.ts(typescript 7.0.2,npm view typescript versionon 2026-11-13, and 5.9.3) and bynode file.ts(Node 24.11).
Commenti
Caricamento commenti...
Sign in to comment