Sub topic 3
unknown: The Type-Safe Alternative to any
This chapter assumes basic TypeScript type annotations, interfaces, union types, and JavaScript’s typeof, instanceof, and try...catch. You should also be able to run tsc or use an editor with TypeScript support.
Why `unknown` exists
External data often has no trustworthy type. It may come from JSON, an API, a browser event, or a JavaScript library. The any type accepts this data, but it also disables checking:
let value: any = "hello";
value.toFixed(); // Compiles, but throws at runtimeunknown also accepts every value, but it does not allow you to use the value until you prove its type.
let value: unknown = "hello";
// value.toUpperCase(); // Error: value is of type 'unknown'
if (typeof value === "string") {
console.log(value.toUpperCase()); // Safe: value is now a string
}The compiler calls this process narrowing. Narrowing changes a broad type into a more specific type after a runtime check.
Checking an `unknown` value
Use checks that JavaScript performs at runtime. typeof works for primitive values. instanceof checks whether an object was created from a particular class. The in operator checks whether an object has a property.
function describe(value: unknown): string {
if (typeof value === "string") {
return `text with ${value.length} characters`;
}
if (typeof value === "number") {
return `number: ${value.toFixed(2)}`;
}
if (value instanceof Date) {
return `date: ${value.toISOString()}`;
}
if (typeof value === "object" && value !== null && "name" in value) {
return "object with a name property";
}
return "some other value";
}
const values: unknown[] = [
"TypeScript",
42,
new Date("2026-01-01"),
{ name: "Ada" },
null,
];
for (const item of values) {
console.log(describe(item));
}The object check must include value !== null because JavaScript reports typeof null as "object". The in check only proves that a property exists. It does not prove the property has the type you expect.
`unknown` at trust boundaries
A trust boundary is a place where data enters your program without being checked. Common examples include JSON.parse, network responses, environment variables, and caught errors. Treating these values as unknown makes the boundary visible.
function readName(input: unknown): string {
if (
typeof input === "object" &&
input !== null &&
"name" in input &&
typeof input.name === "string"
) {
return input.name;
}
throw new Error("Expected an object with a string name");
}
const data: unknown = JSON.parse('{"name":"Ada"}');
console.log(readName(data));A type assertion such as input as { name: string } only tells the compiler to trust you. It performs no runtime validation. Use an assertion only when another mechanism has already established the value’s shape.
Choosing between `any` and `unknown`
| Situation | Better choice | Reason |
|---|---|---|
| Unchecked external data | `unknown` | Requires validation before use |
| A temporary, isolated legacy boundary | `any` | Allows gradual migration |
| A value that truly supports every operation | Rarely `any` | Confirm that this flexibility is intentional |
Avoid allowing any to spread. An any value can flow into typed variables and functions without errors, hiding mistakes far from their source. Replace it with unknown, then add a narrow check or a user-defined type guard when the same validation is needed repeatedly.
Exercise
Why does unknownValue.toUpperCase() fail when unknownValue is typed as unknown, and what should you do first?
Show answer
The compiler cannot prove that the value is a string. First narrow it with a runtime check such as typeof unknownValue === "string", then call toUpperCase() inside that branch.