Sub topic 3
unknown: the type-safe alternative to any
This chapter assumes you know basic TypeScript syntax (annotations, interfaces, union types), the JavaScript operators typeof and instanceof, and try/catch. You should be able to run tsc or use an editor that shows TypeScript errors. The examples assume "strict": true in tsconfig.json.
What unknown is
unknown is the type of a value you know nothing about. Any value can be assigned to it, but you can do almost nothing with it until you prove what it is.
any and unknown both accept every value. They differ in what they let you do afterwards:
- With
any, the compiler stops checking. You can call it, index it, or pass it anywhere. - With
unknown, the compiler keeps checking. You must narrow the value first, with a check the compiler understands, before you can use it.
let a: any = "hello";
a.toFixed(); // compiles, but throws a TypeError at runtime
let u: unknown = "hello";
// u.toUpperCase(); // error: 'u' is of type 'unknown'
if (typeof u === "string") {
console.log(u.toUpperCase()); // OK: u is narrowed to string
}Both variables hold the same string. The any version compiles even though toFixed does not exist on strings, so the mistake appears only at runtime. The unknown version rejects the unchecked call at compile time and allows it only inside the typeof check.
Why unknown is a top type
Think of a type as a set of values. string is the set of all strings, and string | number is the set of all strings plus all numbers. A type A can be assigned to a type B when every value in A is also in B.
unknown is the set of all values. Every other type is a subset of it, so every type is assignable to unknown. That makes it a top type.
const values: unknown[] = [1, "two", { three: 3 }, null, undefined, () => 4];Going the other way is restricted. A value of type unknown is assignable only to unknown and any. Assigning it to anything narrower fails:
declare const input: unknown;
const x: unknown = input; // OK
const y: any = input; // OK
// const s: string = input; // error: Type 'unknown' is not assignable to type 'string'This one-way rule is the source of the safety. Values flow into unknown freely, and they flow out only after you check them.
What you can and cannot do with unknown
The compiler blocks nearly every operation on an unknown value, because it cannot know the operation is valid.
| Operation on an `unknown` value | Allowed? |
|---|---|
| Assign it to `unknown` or `any` | Yes |
| Compare with `===`, `!==`, `==`, `!=` | Yes |
| Use `typeof`, `instanceof`, or `in` checks on it | Yes |
| Use it in a `!` or `&&` truthiness test | Yes |
| Read a property, call it, or index it | No |
| Use arithmetic, `+`, or `<` on it | No |
| Assign it to a more specific type | No |
| Spread it or iterate over it | No |
Equality and truthiness checks are allowed because they are valid for every JavaScript value. Everything else depends on the value's real type, so the compiler requires evidence first.
Narrowing: how unknown becomes usable
Narrowing is the compiler's process of refining a type inside a block of code based on a check. Chapter-by-chapter, later material covers each technique in detail. Here you only need the idea: after a successful check, the compiler treats the variable as a more specific type inside that branch.
function describe(value: unknown): string {
if (typeof value === "string") {
return `string of length ${value.length}`;
}
if (typeof value === "number") {
return `number ${value.toFixed(2)}`;
}
if (Array.isArray(value)) {
return `array with ${value.length} items`;
}
return "something else";
}Inside the first if, value is string, so .length is valid. Inside the second, it is number. Array.isArray narrows to any[], which is why value.length works in the third branch. Outside all three, value is still unknown.
Narrowing lasts only as long as the compiler can follow the control flow. If you store the checked value in another variable of a wider type, or the check is hidden inside a helper function without a type predicate, the narrowing is lost.
function isNonEmptyString(value: unknown): boolean {
return typeof value === "string" && value.length > 0;
}
function shout(value: unknown): string {
if (isNonEmptyString(value)) {
// return value.toUpperCase(); // error: value is still unknown
return String(value).toUpperCase();
}
return "";
}The helper returns a plain boolean, so the compiler learns nothing from it. A later chapter shows how to declare a return type of value is string to fix this.
unknown in unions and intersections
unknown has special behavior when combined with other types. These rules follow from the set model.
| Expression | Result | Reason | Column |
|---|---|---|---|
| `unknown \ | string` | `unknown` | The union of "everything" and anything is everything. |
| `unknown & string` | `string` | The overlap of "everything" and `string` is `string`. | |
| `unknown & never` | `never` | The overlap with the empty set is empty. | |
| `unknown \ | any` | `any` | `any` overrides `unknown` in a union. |
| `unknown & any` | `any` | `any` also wins in an intersection. |
The practical consequence: a union that contains unknown collapses to unknown, so writing string | unknown gives you no hint about string. If you want autocompletion for known cases plus a fallback, unknown is the wrong tool.
Using unknown in function signatures
Use unknown for parameters when a function accepts anything and decides what to do by inspecting the value. Logging, serialization, and validation helpers fit this pattern.
function formatForLog(value: unknown): string {
if (typeof value === "string") return value;
if (value instanceof Error) return `${value.name}: ${value.message}`;
try {
return JSON.stringify(value) ?? String(value);
} catch {
return String(value);
}
}
console.log(formatForLog(new Error("boom")));
console.log(formatForLog({ id: 7 }));
console.log(formatForLog(undefined));The function accepts any argument, yet the body must check before it touches a property. If you declared the parameter as any, you could write value.message directly and never notice that most inputs do not have a message.
Use unknown for return types with care. A function that returns unknown pushes the checking work onto every caller. That is the right trade for functions that really return untyped data, such as a parser. It is the wrong trade when you could return a precise type.
Common errors with unknown
These mistakes are the ones intermediate developers meet most often.
- Using a property without narrowing. Writing
value.nameon anunknownvalue is an error. Add a check, such astypeof value === "object" && value !== null && "name" in value. - Forgetting
null.typeof nullis"object". Aftertypeof value === "object", the type isobject | null, so reading a property still fails until you excludenull. - Silencing the error with
as. Writing(value as User).namecompiles, but it only asserts. Nothing checks it at runtime, so you get the same risk asanywith extra typing. Assertions are covered in a later chapter. - Assuming a check narrows when it does not. A check that returns a plain
booleanfrom a helper does not narrow, as shown above. - Using
unknownwhere a union would do. If the possible types are known, such asstring | number, declare that union. It gives better completion and error messages thanunknown.
declare const input: unknown;
if (typeof input === "object") {
// input is 'object | null' here
// console.log(input.length); // error: 'input' is possibly 'null'
}
if (typeof input === "object" && input !== null) {
// input is 'object'; still no known properties
if ("length" in input) {
console.log(input.length); // unknown (TypeScript 4.9 or later)
}
}After excluding null, input is object, which has no known properties. The in check adds the property to the type as unknown, so you must narrow that again before using it. This repeated narrowing is the cost of safety, and it is why larger shapes are better handled by a type guard.
any versus unknown at a glance
| Question | `any` | `unknown` |
|---|---|---|
| Accepts every value | Yes | Yes |
| Can be assigned to any type | Yes | No, only to `unknown` and `any` |
| Allows property access and calls | Yes | No, not until narrowed |
| Spreads to inferred types | Yes, `any` is contagious | No |
| Errors caught by the compiler | Few | Most misuse |
any spreads: if you read a property from an any value, the result is also any, and so on down the chain. A single any at an input boundary can silently disable checking across a whole call graph. unknown does not spread, because every use requires a check that produces a concrete type.
Summary of the model
unknownis the set of all values, so any value can be assigned to it.- It can be assigned out only to
unknownandany. - Operations beyond equality and truthiness need narrowing first.
- Narrowing happens inside branches where the compiler can follow your check.
unknownabsorbs other types in a union and disappears in an intersection.
Exercise
The function below compiles, but it has a bug that appears when value is null. Rewrite it so it compiles with value: unknown and never throws for null. What does it return for null, { name: "Ada" }, and 42?
function getName(value: unknown): string {
if (typeof value === "object") {
return (value as { name: string }).name;
}
return "unknown";
}
Show answer
The original asserts with as, and typeof null === "object" lets null through, so null.name throws a TypeError. A safe version excludes null, checks the property, and checks its type:
function getName(value: unknown): string {
if (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string"
) {
return value.name;
}
return "unknown";
}
It returns "unknown" for null, "Ada" for { name: "Ada" }, and "unknown" for 42. The in narrowing of value.name requires TypeScript 4.9 or later.
Exercise
What are the types of unknown | string, unknown & string, and unknown & never, and why?
Show answer
unknown | string is unknown, because the union of the set of all values with any other set is the set of all values. unknown & string is string, because the overlap of all values with strings is strings. unknown & never is never, because the overlap with the empty set is empty.