The state that should not exist and yet can be written
Think of the way almost everyone describes loading data from a network: an object with a boolean saying whether it is loading, a field for the data and one for the error message, both optional. It looks reasonable, and it lets you write combinations that mean nothing: data and error together, or a load in progress that already has an error and data.
There are eight possible combinations: two values of the boolean, times two possibilities (present or absent) for the data field, times two for the error. Four have a name anyone understands: idle, loading, succeeded, failed. The other four are data plus error, with or without loading, and loading together with data or with an error. They can make sense if you decide so, for example a refresh that restarts with the old data or a retry after an error, but the type does not say which. So every point of the program that meets them invents its own meaning, and the inconsistency shows up in the view, where one branch checks the boolean, another checks whether the data is present, and the two can be true together.
The solution is not to handle those four states better. It is to make them impossible to write, so
that the compiler rejects the code that builds them. The tool is called a discriminated union, and
the part worth learning is not the syntax: it is the check that warns you when you add a case and
forget to handle it. You need to know how to narrow a type with a guard, which is the subject of
article 03 on type guards,
and why data arriving from outside must be treated as unknown, as in
article 02: the discriminated
union is for values the program builds itself, and the boundary with the outside world remains a
separate problem.
All the compiler errors reported here are those of TypeScript 7.0.2, the latest
version on the npm registry on 2026-11-13, installed in a test project with strict on;
the 7 series is the compiler rewritten in Go, announced on 8 July 2026. The same files tried with
5.9.3 give the same codes and the same positions. Every block is the file I compiled, with the real
output at the end.
The flat shape: the compiler approves the meaningless states
Before building the solution it is worth looking at the compiled problem, because the point is not that the flat shape is ugly: it is that the compiler approves it without a word.
// One boolean and two optional fields: 2 x 2 x 2 = eight combinations.
export interface StatoPiatto<T> {
caricamento: boolean;
dati?: T;
errore?: string;
}
// This one is legitimate: no request in flight, no data, no error.
export const inattivo: StatoPiatto<number> = { caricamento: false };
// These two compile and describe no state of the interface:
// data and error together, and the second while loading as well.
export const datiEErrore: StatoPiatto<number> = { caricamento: false, dati: 42, errore: 'failed' };
export const tuttoInsieme: StatoPiatto<number> = { caricamento: true, dati: 42, errore: 'failed' };
// Output of tsc 7.0.2: no errors.
The compiler has nothing to say about the three constants. The first, inattivo, is
legitimate: no request in flight, no data, no error. The other two are the ones the type should not
let through. datiEErrore declares a success and a failure at the same time, and
tuttoInsieme adds a load in progress. There is no way to know which of the three fields
tells the truth, and the type is describing eight combinations of which four are defects waiting to
reach the view.
One type per state, with a field that tells them apart
// Four states, and no field that exists where it makes no sense.
export type StatoRichiesta<T> =
| { fase: 'inattivo' }
| { fase: 'caricamento'; iniziatoA: number }
| { fase: 'successo'; dati: T }
| { fase: 'errore'; messaggio: string };
export function etichetta<T>(stato: StatoRichiesta<T>): string {
switch (stato.fase) {
case 'inattivo':
return 'No request';
case 'caricamento':
return 'Loading';
case 'successo':
return 'Data ready';
case 'errore':
return `Error: ${stato.messaggio}`;
default:
return controlloEsaustivo(stato);
}
}
// In the default branch the type is never only if the cases above cover them all.
function controlloEsaustivo(valore: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(valore)}`);
}
const stati: StatoRichiesta<number>[] = [
{ fase: 'inattivo' },
{ fase: 'caricamento', iniziatoA: 1000 },
{ fase: 'successo', dati: 42 },
{ fase: 'errore', messaggio: 'timeout' },
];
for (const s of stati) console.log(etichetta(s));
// A value coming from outside (JSON, for example) may not respect the type.
try {
etichetta(JSON.parse('{"fase":"annullato"}') as StatoRichiesta<number>);
} catch (e) {
console.log((e as Error).message);
}
// Output of tsc 7.0.2: no errors.
// Output of node 24.11.0:
// No request
// Loading
// Data ready
// Error: timeout
// Unhandled case: {"fase":"annullato"}
In the block, StatoRichiesta lists four alternative shapes, and etichetta
walks through them with a switch on the fase field. Inside each
case the compiler has already narrowed the type: in the 'errore' branch
stato.messaggio exists, and writing it elsewhere would not compile. The Node output
shows the four states and, on the last line, the case of a value that arrives from outside with a
phase the type does not know: the function throws and says which value it received, instead of
returning a wrong string. Node 24 strips the types without compiling, so that JSON.parse
with a cast is exactly the situation in which the compiler had no jurisdiction.
The fase field is the discriminant, and it is the property on which everything is
decided. It must have three characteristics, and each has a practical consequence if it is missing.
The three tests are in a single file, with the three breakages one after the other.
// 1. Discriminant declared as string: the declaration compiles, the narrowing does not.
type StatoLargo =
| { fase: string }
| { fase: string; dati: number };
export function leggiLargo(s: StatoLargo): number {
if (s.fase === 'successo') {
return s.dati;
}
return 0;
}
// 2. Two branches with the same value: the compiler cannot tell which one it is.
type StessoValore =
| { fase: 'errore'; messaggio: string }
| { fase: 'errore'; codice: number };
export function leggiStesso(s: StessoValore): string {
if (s.fase === 'errore') {
return s.messaggio;
}
return '';
}
// 3. A branch without the discriminant: it cannot even be read.
type SenzaCampo =
| { fase: 'successo'; dati: number }
| { dati: string };
export function leggiSenza(s: SenzaCampo): number {
if (s.fase === 'successo') {
return s.dati;
}
return 0;
}
// Output of tsc 7.0.2:
// 04-discriminante.ts(8,14): error TS2339: Property 'dati' does not exist on type 'StatoLargo'.
// Property 'dati' does not exist on type '{ fase: string; }'.
// 04-discriminante.ts(20,14): error TS2339: Property 'messaggio' does not exist on type 'StessoValore'.
// Property 'messaggio' does not exist on type '{ fase: "errore"; codice: number; }'.
// 04-discriminante.ts(31,9): error TS2339: Property 'fase' does not exist on type 'SenzaCampo'.
// Property 'fase' does not exist on type '{ dati: string; }'.
// 04-discriminante.ts(32,5): error TS2322: Type 'string | number' is not assignable to type 'number'.
// Type 'string' is not assignable to type 'number'.
The first case is a discriminant declared string. The declaration of the union compiles
without a warning, and that silence is the dangerous part; the error comes later, when you try to
read s.dati after the comparison with 'successo', because a comparison
with an arbitrary string does not let the compiler choose the branch. The field must therefore have
a literal type, that is 'successo' and not string.
The second case is two branches with the same value: the comparison with 'errore' does
not tell them apart, and s.messaggio is not readable because it could be the branch
with codice. The values must be different across the branches. The
third is a branch without the field: even reading s.fase is an error, because the
property does not exist on every member, and the field must be present in all of
them. Note also the last error, which is a consequence: without the narrowing,
s.dati is string | number, and does not fit into a number.
The name of the field is free: fase, tipo, kind or
stato work identically, and the convention matters only for readability. What is not
free is the position of the data: dati exists only in the success
branch and messaggio only in the error one. It is this, and not the discriminant, that
makes the state with data and an error together impossible: no member of the union declares both
fields.
The generic parameter T carries the type of the data without the union having to know
it: the value passes through this structure and is never read inside it, so the type is preserved
and not checked. The iniziatoA field on the loading branch shows the real strength of
the pattern: each state can carry the data that is needed by that state, and a
start timestamp makes sense only while loading. In an object with optional fields that field would
have been one more empty field for three states out of four.
Set side by side, the two types differ on four points, independent of one another, and each solves a different problem.
- The number of representable states drops from eight to four, and the four that remain are exactly the ones that have a meaning.
- The data is no longer optional: in the success branch
datiis required, so there is no success without a payload. - Each state can carry fields of its own, like
iniziatoAon loading, which in the flat shape would have been a fourth empty field for three states out of four. - Adding a new state becomes a compile error at every point that consumes the type, instead of a missing branch that nobody notices.
The fourth point is the one that justifies the cost of the other three, and the next sections prove it. The first three are gains in precision that you can also obtain with discipline and code review; the fourth is a mechanical check that keeps working when the program grows and whoever modifies it is no longer the person who wrote it.
The check that warns you when the union grows
The part of the block that looks strange is the final function, the one that accepts a parameter of
type never. It is not an academic curiosity: it is the reason this pattern holds up
over time, and it is easier to understand by watching it fail.
never is the type with no possible value. When the compiler has examined all the
branches of a union inside a switch, in the default branch the type of the
variable has been reduced to never, because no possibility is left. Passing it to a
function that accepts never is therefore legal. If instead a case is not handled, that
case remains in the default, and a type with values is not assignable to
never: the Handbook says that never is assignable to every type but no
type is assignable to never, except never itself. The check fires at
compile time. Here is the same file without the 'errore' case:
export type StatoRichiesta<T> =
| { fase: 'inattivo' }
| { fase: 'caricamento'; iniziatoA: number }
| { fase: 'successo'; dati: T }
| { fase: 'errore'; messaggio: string };
export function etichetta<T>(stato: StatoRichiesta<T>): string {
switch (stato.fase) {
case 'inattivo':
return 'No request';
case 'caricamento':
return 'Loading';
case 'successo':
return 'Data ready';
default:
return controlloEsaustivo(stato);
}
}
function controlloEsaustivo(valore: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(valore)}`);
}
// Output of tsc 7.0.2:
// 03-caso-mancante.ts(16,33): error TS2345: Argument of type '{ fase: "errore"; messaggio: string; }' is not assignable to parameter of type 'never'.
The message is better than any comment: it does not say "you forgot a case", it says
which one, with all its fields, and it points to line 16, column 33, that is to the
argument passed to the check. The day someone adds an 'annullato' state to the union,
every switch in the project that consumes it breaks at compile time, and the message
names the new state. It is the difference between a refactoring done by following the errors and one
done by searching with grep and hoping you found everything.
A clarification on why the function declares never as its return type. Since
TypeScript 3.7 the compiler treats the call to a function that declares never as a
point from which there is no exit: the release notes of that version explain it, where the
return in front of process.exit(1) is no longer needed. I tried what
changes in our case, by removing the return in front of the call.
type Stato = { fase: 'a' } | { fase: 'b' };
function esaurito(valore: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(valore)}`);
}
// Without "return" in front of the call, with noImplicitReturns on.
export function etichetta(s: Stato): string {
switch (s.fase) {
case 'a':
return 'A';
case 'b':
return 'B';
default:
esaurito(s);
}
}
// Same thing, but the function has NO declared return type.
const esauritoSenzaAnnotazione = (valore: never) => {
throw new Error(`Unhandled case: ${JSON.stringify(valore)}`);
};
export function etichetta2(s: Stato): string {
switch (s.fase) {
case 'a':
return 'A';
case 'b':
return 'B';
default:
esauritoSenzaAnnotazione(s);
}
}
// Output of tsc 7.0.2:
// 05-niente-return.ts(24,39): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
The first etichetta compiles: the call to esaurito, declared with an
explicit never, closes the path. The second does not, and the TS2366 error is at line
24: the helper function is an arrow expression without the type written out, and for the compiler
the call is no longer a point of no return, so the function can end without a value. Two notes to
avoid misunderstandings. The error appears identically even without the
noImplicitReturns option (I tried it), so it is not that option that decides. And the
throwing part, in the body of controlloEsaustivo, serves another purpose: it protects
at run time against the value that arrives from outside, where the compiler had no jurisdiction, and
in that case failing immediately and saying which value arrived is better than returning an empty
string.
It remains to understand when the function with the default is really needed, and when
you would be protected anyway without it. The last file shows the difference.
type Stato = { fase: 'a' } | { fase: 'b' } | { fase: 'c' };
// It returns a value: with a missing case the compiler notices on its own.
export function etichetta(s: Stato): string {
switch (s.fase) {
case 'a':
return 'A';
case 'b':
return 'B';
}
}
// It returns nothing: with a missing case the compiler stays silent.
export function registra(s: Stato): void {
switch (s.fase) {
case 'a':
console.log('A');
break;
case 'b':
console.log('B');
break;
}
}
// Output of tsc 7.0.2:
// 06-senza-default.ts(4,38): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
For a function that returns a value, the compiler notices a missing case on its own: TS2366, at
line 4. The message, however, does not say which case is missing. For a function
that returns nothing, like registra, it says nothing at all: the incomplete
switch passes in silence, and the 'c' case is ignored. That is where the
default with the check on never earns its place, and elsewhere it at least
gives you the name of the case.
What you lose, because something is always lost
The pattern has a price and it should be stated, because honest comparisons are more useful than
advice. Writing and reading these states is more verbose: you can no longer touch
stato.dati directly, you must first go through the check on the phase. In a template
this means one branch per state instead of a couple of conditions, and on very simple states it is
extra work with no gain.
The threshold I use to decide is the number of illegal combinations. With one boolean and a single optional field the combinations are four and almost all have a meaning, so the cost of handling them by hand is low. From three fields up the count grows as a power of two, and the discriminated union becomes the least costly choice, not the most rigorous. The other signal, more reliable than the count, is of a different nature: if you catch yourself writing a comment that explains which combinations of fields are valid, that comment is a type you have not written.
There is a second price, less obvious: the check with never protects where you write
it, and nowhere else. A chain of if works exactly like a switch if the
final branch demands never; if the final branch is a generic else, the new
case ends up inside it without an error.
type Stato =
| { fase: 'inattivo' }
| { fase: 'successo'; dati: number }
| { fase: 'errore'; messaggio: string };
function esaurito(valore: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(valore)}`);
}
// Chain of ifs whose final branch demands never: it covers everything.
export function conControllo(s: Stato): string {
if (s.fase === 'inattivo') {
return 'idle';
} else if (s.fase === 'successo') {
return `data: ${s.dati}`;
} else {
return esaurito(s);
}
}
// Same chain, but the final branch is a generic else: the 'errore' case ends up there.
export function senzaControllo(s: Stato): string {
if (s.fase === 'inattivo') {
return 'idle';
} else if (s.fase === 'successo') {
return `data: ${s.dati}`;
}
return 'other';
}
// Output of tsc 7.0.2:
// 07-catena-if.ts(17,21): error TS2345: Argument of type '{ fase: "errore"; messaggio: string; }' is not assignable to parameter of type 'never'.
The first function, conControllo, does not compile because in this experiment I left
out the error branch: the compiler names it, at line 17. The second, which closes with
return 'other', produces no error, and that fallback value hides the forgotten case. A
template or an expression that does not contain the check is in the same situation, a line of
reasoning I did not try on a framework template. For this reason it is better to route the decision
through a single function that returns what the view needs, like etichetta, instead of
distributing the state logic across the view itself.
Four signals say it is time to move to the discriminated union. They can be recognized independently of one another, and one is enough.
- You are writing a comment that explains which combinations of fields are valid: that comment is a type you have not written.
- At some point in the code you read an optional field with an exclamation mark or a cast, because "it is surely there".
- A test has to build an object with fields it does not need, only to satisfy the type.
- In the view two conditions can be true together and the order of the branches decides what is shown: it is the symptom that the states overlap.
The four signals share one fact: the code knows something about the state that the type does not know. The exclamation mark and the cast are the most visible form, because they say "trust me" to the compiler; the fix is to move that knowledge into the type, so that it no longer has to be repeated at every point of reading.
What you can do now
You can now recognize the symptom, that is an object with several optional fields that together describe a state, and you know that the number of illegal states that type authorizes grows as a power of two. You can build the discriminated union that makes them inexpressible, and you know the three conditions on the discriminant, each with the error the compiler produces if you break it: literal type, a different value in every branch, a field present in all of them.
You can also add the exhaustiveness check with never, and you know what the compiler
answers when a case is missing: it names the forgotten case with all its fields. You know it matters
above all where a function does not return a value, and that it holds where you write it. You can
run the proof right now, by adding a fifth state to your union and counting how many points of the
program refuse to compile. Those are the points you would have had to find by hand.
In the next article, 05 on
satisfies, the same precision is applied to an object literal, such as a catalog of
entries: why annotating it with an interface destroys the information about its keys, and what to
use instead. The start of the series, on the escape routes that strict leaves open, is
in article 01.
Frequently asked questions
What is a discriminated union?
A type made of several alternative shapes, each with a common field whose literal value is different in each one. The compiler uses that field to tell which shape it is dealing with and narrows the type accordingly, so the fields of one shape are not readable in the others.
Why can the discriminant not be of type string?
Because narrowing works only on literal types. Declaring the field as string compiles without errors, but then reading a field specific to a branch, after the comparison, produces the TS2339 error: the compiler can no longer choose the branch.
What is a function that accepts a never parameter for?
To check exhaustiveness. In the default branch of a switch that covers every case, the type has been reduced to never and the assignment is legal. If a case is missing, that case remains in the default, is not assignable to never, and the compiler reports it by naming it.
Does the exhaustiveness check also work on ifs?
Yes, if the final branch of the chain demands never, just like the default of a switch. If the final branch is a generic else or a fallback value, a new case ends up inside it with no error at all. The check holds where you write it.
When is a discriminated union not worth using?
When the illegal combinations are few, that is with one boolean and a single optional field: the cost of handling them by hand is lower than the verbosity of the type. The signal that the threshold has passed is usually a comment explaining which combinations of fields are valid, because that comment is an unwritten type.
The same series also includes Template literal types.
Sources
- TypeScript Handbook - Narrowing: the passage on discriminated unions, on the
nevertype and on the exhaustiveness check, read; consulted on 2026-11-13. - TypeScript 3.7 - release notes: the passage on functions that return
neverand on control flow, read; consulted on 2026-11-13. - Announcing TypeScript 7.0: the date (8 July 2026) and the nature of the compiler used for the tests, only the opening read; consulted on 2026-11-13.
- The errors and the Node outputs are produced by the commands
tsc --noEmit --strict --noImplicitReturns --target ES2022 --module ESNext --moduleResolution bundler file.ts(typescript 7.0.2,npm view typescript versionon 2026-11-13) andnode file.ts(Node 24.11).
Commenti
Caricamento commenti...
Sign in to comment