Sub topic 11
any versus unknown
This chapter assumes you know union types, typeof narrowing, and what strict mode turns on in tsconfig.json. Both any and unknown describe a value whose type you don't know. They differ in what the compiler lets you do with that value.
What each type means
any switches off type checking for a value. You can read any property, call it, pass it anywhere, and assign it to any other type.
unknown is the type of "some value, not yet inspected". Anything can be assigned to it. Nothing can be done with it until you narrow it.
In the type hierarchy, unknown is the top type, so every type is assignable to it. any is both a top type and a bottom type. It is assignable to everything, and everything is assignable to it, so it ignores the usual rules.
any removes the safety net
const data: any = "hello";
const length: number = data.length; // fine, data really is a string
const wrong: number = data; // allowed: any is assignable to number
data.foo.bar.baz; // allowed: no property checks
data.toFixed(2); // allowed, but throws a TypeError at runtimeNone of these lines produces a compile error. The last one fails only when the program runs. Editor autocompletion also disappears for data, because the compiler has no information to offer.
any spreads
The worst property of any is that it spreads. A value derived from an any is usually any as well.
const parsed = JSON.parse("[1, 2, 3]"); // JSON.parse returns any
const count = parsed.length; // count is any
const doubled = parsed.map((n) => n * 2); // doubled is any, n is anyOne any at the edge of your program can turn large parts of the code into unchecked territory. You will not see an error. You will just lose protection.
unknown forces a check
const raw: unknown = JSON.parse("42");
// raw.toFixed(2); // Error: 'raw' is of type 'unknown'.
// const n: number = raw; // Error: Type 'unknown' is not assignable to type 'number'.
if (typeof raw === "number") {
console.log(raw.toFixed(2)); // raw is number here
}The only operations allowed on an unknown value directly are the ones that are safe for every value:
- Comparisons with
===,!==,==, and!=. typeofandinstanceofchecks.- Passing it to something that accepts
unknown, or assigning it toanyorunknown. - Template string interpolation and
String(value).
Everything else needs narrowing first.
Narrowing unknown
The narrowing tools you already know from unions work on unknown too. Each one gives the compiler enough evidence to assign a concrete type.
function format(value: unknown): string {
if (typeof value === "string") {
return value.trim();
}
if (typeof value === "number") {
return value.toFixed(1);
}
if (value instanceof Date) {
return value.toISOString();
}
if (Array.isArray(value)) {
return `array of ${value.length}`;
}
return String(value);
}
console.log(format(3.14159)); // 3.1Array.isArray narrows unknown to any[], so the elements inside are any again. Narrow the elements separately if you use them.
For objects, the in operator narrows to a type that has the named property (TypeScript 4.9 and later):
function readId(value: unknown): number | undefined {
if (typeof value === "object" && value !== null && "id" in value) {
// value is now: object & Record<"id", unknown>
return typeof value.id === "number" ? value.id : undefined;
}
return undefined;
}
console.log(readId({ id: 7 })); // 7Notice that typeof value === "object" also matches null, so the value !== null check is required. The compiler enforces this: without it, "id" in value is an error.
Writing a type guard for external data
When the same checks repeat, put them in a function whose return type is a type predicate. The predicate v is User tells the compiler that a true result means v is a User.
interface User {
id: number;
name: string;
}
function isUser(v: unknown): v is User {
if (typeof v !== "object" || v === null) {
return false;
}
const record = v as Record<string, unknown>;
return typeof record.id === "number" && typeof record.name === "string";
}
const parsed: unknown = JSON.parse('{"id": 1, "name": "Ada"}');
if (isUser(parsed)) {
console.log(parsed.name.toUpperCase()); // ADA
} else {
console.log("Not a user");
}The as Record<string, unknown> inside the guard is a deliberate, local assertion. The typeof checks right after it do the real verification. The compiler does not check that a predicate matches its body. If you forget a field check, isUser will still compile and will lie to every caller.
Where unknown appears and where any leaks in
| Source | Type you get | What to do |
|---|---|---|
| `JSON.parse(text)` | `any` | Assign to `unknown` immediately, then validate |
| `catch (error)` | `unknown` with `strict` (via `useUnknownInCatchVariables`) | Check `error instanceof Error` |
| `response.json()` from `fetch` | `Promise<any>` | Annotate as `unknown` and validate |
| Untyped function parameter | Implicit `any` | Enable `noImplicitAny` (part of `strict`) |
| `Array.isArray(x)` on `unknown` | `any[]` | Narrow the elements before use |
The catch clause is the most common first encounter with unknown:
try {
JSON.parse("{ not json");
} catch (error) {
if (error instanceof SyntaxError) {
console.log("Bad JSON:", error.message);
} else {
console.log("Unexpected failure:", String(error));
}
}JavaScript lets code throw anything, including strings and numbers. That is why unknown is the accurate type for error, and why error.message without a check is not safe.
Edge cases with the top types
- Unions absorb:
string | unknownisunknown, andstring | anyisany. Adding either to a union erases the other members. - Intersections reduce:
string & unknownisstring, becauseunknownis the identity for&.string & anyisany. - Assignability is one-way:
unknowncan be assigned only tounknownandany. A value typedunknowncannot be passed to a function that expectsstring. - Mapped and generic types: a generic
T extends unknownaccepts everything, which is a safe way to say "no constraint". Usingany[]or(...args: any[]) => anyas a constraint is a common and accepted use ofany, because it must accept every function signature. - Implicit any: with
noImplicitAnyoff, a parameter with no annotation silently becomesany. With it on, you get an error and must choose a type.
Choosing between them
As a working rule:
- Default to
unknownfor data you did not create: parsed JSON, network responses, user input, thrown values. - Use
anyonly where the type system cannot express what you need, and keep it contained. Wrap it in a function with a typed signature so it does not spread. - During a JavaScript-to-TypeScript migration,
anyis a temporary marker. Searching for: anyshows you the remaining work. Lint rules such as@typescript-eslint/no-explicit-anyhelp you track it.
The trade-off is effort. unknown costs you a few lines of checking at the boundary. In return, every later use of the validated value is fully checked. For large or nested shapes, hand-written guards get tedious, and a schema validation library is the usual next step. That library does the same job: it takes unknown and returns a typed value or an error.
Exercise
A function load(text: string) returns JSON.parse(text) and is declared with no return type. Callers write load(input).user.name.toUpperCase(). What is the inferred return type, why is this risky, and how would you change the function?
Show answer
The inferred return type is any, because JSON.parse returns any. Callers get no checking, so a missing user or a non-string name fails only at runtime. Declare the return type as unknown, for example function load(text: string): unknown { return JSON.parse(text); }. Callers must then narrow the result, for example with a type guard such as isUser, before reading .user.name.
Exercise
Given const v: unknown = getValue();, which of these lines compile under strict? (a) const s: string = v; (b) const t: unknown = v; (c) if (typeof v === "string") { v.length; } (d) v.length;
Show answer
(b) and (c) compile. (a) fails because unknown is not assignable to string. (d) fails because you cannot access properties on unknown without narrowing first.