Skip to main content

02 - unknown instead of any: the boundary where data enters the program

On a boundary, nobody checks the type you wrote. unknown makes it checkable: real compiler errors and the honest cost of the choice.

What do you think about this article?

02 - unknown instead of any: the boundary where data enters the program
TypeScript Avanzatofedericocalo.dev

At a Glance

On a boundary, nobody checks the type you wrote. unknown makes it checkable: real compiler errors and the honest cost of the choice.

The point where the type you wrote stops being true

Inside your program, types are a serious matter: you write them, the compiler checks them, and if you get it wrong it tells you. Then comes a line that reads an HTTP response, or a string from the browser's storage, or the body of a queue message, and at that point the type is no longer a check: it is a hope. Nobody has verified anything. You wrote that the thing is a Profilo, and the compiler took your word for it.

That point is called a boundary, and an application has few of them: network calls, reads from local storage, parameters in the address, queue messages, the contents of a file. They are few, and they are all the places where the hardest-to-read errors are born, because the failure shows up far from the point where the bad data came in. This article is about a single decision, to be made at each of those boundaries: writing any or unknown there, and what really changes. If you first need the overall picture of how many escape hatches remain in a strict project, it is the previous article.

The two types look alike and do the opposite

Both accept any incoming value, and that is where the similarity ends. The difference is in what they let you do afterwards. With any you can do everything: read a property, call it as a function, use it in an addition. None of these operations is checked, and any is contagious, because the result of an operation on any is still any, and the hole widens along the data's path.

With unknown you can do nothing until you prove what it is. That is not a limitation: it is the whole feature. unknown moves the moment of checking from the point where you know nothing to the point where you have just verified, and connects them. You pay the price immediately, in lines of code, and only once.

The quickest way to see the difference is something this project already has switched on without having chosen it explicitly. Among the nine checks that strict turns on is useUnknownInCatchVariables, and its effect is exactly this: the variable of a catch block is not any but unknown. It is the reason why, in this repository, error handling is written like this and not more briefly.


// useUnknownInCatchVariables (on with strict) types 'err' as unknown.
export function messaggioDiErrore(err: unknown): string {
  if (err instanceof Error) {
    return err.message;
  }
  if (typeof err === 'string') {
    return err;
  }
  return 'Errore sconosciuto';
}
      

Three things in this block are the substance of the article, and they are worth naming one by one.

err instanceof Error is a narrowing: a check the compiler recognizes and trusts, because it inspects the prototype chain at runtime. Inside that if, and only there, err has type Error, so err.message is a verified read and not a claim. Note that it does not hold for every thrown value: in JavaScript you can throw anything, strings and numbers included, which is why the block has a second branch.

typeof err === 'string' is the second form of narrowing, the one that works on primitive types. The two cover different cases and are not interchangeable: instanceof works on classes and does not work on primitives, typeof works on primitives and returns 'string' for a string, but returns 'object' for any object and so tells you nothing.

The final return exists because, with strictNullChecks, a function that declares it returns string must return one on every path, and the path where the thrown value is neither an Error nor a string is a real path. Tested: without that line the compiler answers error TS2366: Function lacks ending return statement and return type does not include 'undefined'., with or without noImplicitReturns, while with --strict false the error disappears, because undefined belongs to every type. It is one more reason not to switch strict off. The case, moreover, really happens: a Promise.reject() with no arguments throws undefined, and the block handles it.

What the compiler says when you skip the step

All the blocks in this article were compiled with that version and those three flags, and the outputs reported are the real ones. With this version strict is on even when you do not write it: a file passed to tsc with no options at all gave the same TS2366. It is worth seeing the real error, because it is the one you will meet and it is more precise than tutorials remember. This is the wrong version, the one that reads the message directly:


export async function avvia(operazione: () => Promise<void>): Promise<string | null> {
  try {
    await operazione();
    return null;
  } catch (err) {
    // 'err' is unknown: reading .message directly does not compile.
    return err.message;
  }
}
      

Compiled with tsc 7.0.2, the current version on npm on 13 November 2026, and with strict, noImplicitReturns and noPropertyAccessFromIndexSignature switched on, it produces this:


02-catch-sbagliato.ts(7,12): error TS18046: 'err' is of type 'unknown'.
      

The code TS18046 says one thing only, and it is not about message: it says the variable is of type unknown. The compiler does not complain about the field you asked for, it complains that you do not know what you are asking it of. It is a distinction worth keeping in mind, because the wrong fix for this error, annotating the variable as any, makes it disappear without solving anything.

A real boundary: reading an object from storage

The catch case is useful because the language imposes it. The case you have to write yourself is the other one: a value that arrives from outside as text and must become a typed object. In this project the real scenario is the browser's storage, where a dedicated service reads and writes values under prefixed keys, and the value read is always a string that someone wrote in another version of the application.


export interface Preferenze {
  tema: 'chiaro';
  lingua: 'it' | 'en';
}

function sonoPreferenze(valore: unknown): valore is Preferenze {
  if (typeof valore !== 'object' || valore === null) {
    return false;
  }
  const o = valore as Record<string, unknown>;
  return o['tema'] === 'chiaro' && (o['lingua'] === 'it' || o['lingua'] === 'en');
}

export function leggiPreferenze(grezzo: string | null, scorta: Preferenze): Preferenze {
  if (grezzo === null) {
    return scorta;
  }
  let analizzato: unknown;
  try {
    analizzato = JSON.parse(grezzo);
  } catch {
    return scorta;
  }
  return sonoPreferenze(analizzato) ? analizzato : scorta;
}
      

The property of this block worth stopping on is the declaration analizzato: unknown, because it is the one indispensable line. JSON.parse returns any, and this is a detail of the standard library worth knowing: it means that without that declaration the result would propagate as any through the rest of the function, and the guard I wrote below would become decorative. Annotating the variable as unknown is what forces you to go through the check. It is a line that does nothing at runtime and holds everything else up.

The second thing to explain is the signature valore is Preferenze. It is not an ordinary boolean: it is a type predicate, and it tells the compiler that when the function returns true the parameter can be treated as Preferenze. It is the mechanism that makes the last line work, where the conditional operator returns analizzato with no cast. The price of this power is high and is paid once: the compiler does not verify that the checks inside the predicate match the promised type. A predicate that always returns true compiles and lies to the whole program, and it is the trap the next article in the series is about.

Inside the guard, the cast valore as Record<string, unknown> deserves a note, because it seems to contradict the whole article. It does not: it is a cast to a less precise type, not a more precise one. It only asserts that this is an object with text keys and unknown values, which the two lines above have already verified. It is needed because on plain unknown nothing can be indexed, and the read stays safe because every value read is itself unknown and must be compared before being used. The square brackets instead of dot properties are not a preference: with noPropertyAccessFromIndexSignature on, as in this project, reading o.tema on an indexed type does not compile: error TS4111: Property 'tema' comes from an index signature, so it must be accessed with ['tema']. The flag is not part of strict and has to be switched on separately.

Compiling does not prove that the function behaves well, which is why I ran the two blocks with Node 24, which strips the types by itself and runs .ts files. Save the first block as messaggio.ts and the one with the preferences as preferenze.ts, then put this third file next to them and run node prova.ts. The output is identical in two consecutive runs. The Italian strings in the file are data of the experiment and stay as they are: chiaro is the allowed theme, and Errore sconosciuto is the fallback message, "unknown error".


import { messaggioDiErrore } from './messaggio.ts';
import { leggiPreferenze } from './preferenze.ts';
import type { Preferenze } from './preferenze.ts';

const scorta: Preferenze = { tema: 'chiaro', lingua: 'it' };

console.log(messaggioDiErrore(new RangeError('fuori intervallo')));
console.log(messaggioDiErrore('testo lanciato'));
console.log(messaggioDiErrore(404));
console.log(messaggioDiErrore(undefined));

console.log(leggiPreferenze('{"tema":"chiaro","lingua":"en"}', scorta));
console.log(leggiPreferenze('{"tema":"scuro","lingua":"en"}', scorta));
console.log(leggiPreferenze('{"tema":"chiaro"}', scorta));
console.log(leggiPreferenze('non e json', scorta));
console.log(leggiPreferenze('null', scorta));
console.log(leggiPreferenze(null, scorta));

// Output:
// fuori intervallo
// testo lanciato
// Errore sconosciuto
// Errore sconosciuto
// { tema: 'chiaro', lingua: 'en' }
// { tema: 'chiaro', lingua: 'it' }
// { tema: 'chiaro', lingua: 'it' }
// { tema: 'chiaro', lingua: 'it' }
// { tema: 'chiaro', lingua: 'it' }
// { tema: 'chiaro', lingua: 'it' }
      

The first four lines test the three branches of messaggioDiErrore: an Error returns its message, a thrown string passes through as it is, and both a number and undefined end up in the final return. The next six concern leggiPreferenze, and only the first, with the right theme and language, returns the data that was read. A theme other than the allowed one, a missing field, a text that is not JSON, the JSON null (which JSON.parse accepts and which the check on null discards) and the absence of the value all return the fallback. It is the behaviour you need on a boundary: bad data does not get in, and the program does not stop.

The real cost, and when it is not worth it

The honest criticism of unknown is that it moves the cost, it does not eliminate it. On a narrow boundary with few shapes, like the preferences above, the cost is fifteen lines written once and never touched again, and in exchange every downstream read is verified. On a response with forty nested fields, writing the guard by hand becomes a tedious job that gets done badly, and a badly written guard is worse than no guard, because it asserts a guarantee that is not there.

In that case the answer is not going back to any: it is to stop writing guards by hand and use a tool that generates them from a schema, where the description of the data and the check are the same object and cannot diverge. The rule I use to decide is the size of the boundary, not its importance: up to three or four fields the hand-written guard is the simplest thing that works, beyond that you reach for the library.

There is one case where any remains the right answer, and denying it would be dishonest: when the value is never read, only carried. A payload you take from one place and hand over to another without looking inside needs no guarantee at all, and for that case there is a better form than either, namely a generic type variable that preserves the caller's type without your having to know it.

The four questions to ask about every boundary

When you find a boundary in your code, these four questions can be answered in a few seconds and are independent of one another.

  • Where the value comes from: network, local storage, address, queue or file. Each origin has a different probability of containing data from a previous version.
  • Whether the value is read inside or only carried. If it is only carried, no check is needed and the right type is generic.
  • How many different shapes it can have. A single shape is checked by hand, two or three are described with a discriminated union, many more call for a schema.
  • What must happen when the check fails: a fallback value, an error to the user, or a write to the log. This is the answer that is missing most often, and it decides whether the function can return a value or must throw.

The four answers do not weigh the same: the second decides whether you need a check at all, and if the answer is "only carried" the other three are not needed. If the value is read, the third sets the tool and the fourth the behaviour of the function, so a guard written without having decided what to do on failure is half a guard. When the possible shapes are two or three, the model is the discriminated union from article 04 of the series.

Wrapping up

You can now recognize a boundary, and you know that on that boundary unknown is not a cautious version of any, it is its opposite: one checks nothing and spreads, the other lets you do nothing until you have verified. You know the compiler at that point says TS18046 and that it talks about the variable's type, not the field you asked for. You know why JSON.parse must be assigned to a variable declared unknown, and that without that line the rest of the check is worth nothing.

You can test whether this step paid off on your own code right now: search for JSON.parse and look at where the result ends up. If it ends up in a variable typed with the interface you expect, you have an unchecked claim at a point where you believed you had a check.

The most uncomfortable question of all stays open, the one I named without tackling: the type predicate you wrote to verify the data is not itself verified by the compiler. The next article starts from there.

Frequently asked questions

What is the difference between any and unknown if both accept any value?

The difference is in what they let you do afterwards. On any every operation is allowed and unchecked, and the result stays any, so the hole spreads. On unknown no operation is allowed until you narrow the type with a check the compiler recognizes.

Why is the catch variable unknown and not any?

Because the useUnknownInCatchVariables check, one of the nine that strict turns on, types it that way. It is correct: in JavaScript you can throw any value, not just an Error, so before reading message you need an err instanceof Error.

What error does the compiler give if I read a property on unknown?

error TS18046: 'err' is of type 'unknown'. Note that it does not name the property you asked for: it complains that the variable's type is unknown. Annotating it as any makes the message disappear without solving the problem.

Does JSON.parse return a safe type?

No, it returns any. If you assign the result directly to a typed variable, you have an unchecked claim. It should be assigned to a variable declared unknown, and from there you go through an explicit check.

Is it always better to use unknown instead of any?

On a boundary with few shapes, yes, because the cost is a guard written once. On a response with dozens of nested fields a hand-written guard becomes unreliable, and a tool that generates it from a schema is better. When the value is only carried and never read, the right type is neither of the two but a generic type.

The same series also includes satisfies and the keys of a catalog and Template literal types.

Sources and further reading

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects