Unknown Type
In this page:
Basic Unknown Type
A variable typed as unknown can hold a value of any type, much like any, but TypeScript refuses to let you perform operations on it until you've proven what it actually is. This makes unknown the type-safe counterpart to any for genuinely uncertain data.
Example: Basic Unknown Type
let value: unknown = "hello";
// console.log(value.length); // rejected: must narrow the type first
console.log(value);
Checking Unknown Values
A typeof check lets you narrow an unknown value down to a specific type, like string or number, before performing type-specific operations on it. Once inside the narrowed branch, TypeScript treats the value as that specific type automatically.
Example: Checking Unknown Values
let value: unknown = "hello";
if (typeof value === "string") {
console.log(value.length); // safe: TypeScript knows it's a string here
}
Unknown with Objects
When an unknown value might be an object, its structure needs to be verified, for example by checking that a particular property exists, before any of its properties can be safely accessed. Skipping this check and accessing a property directly is a compile-time error.
Example: Unknown with Objects
let value: unknown = { name: "Ira" };
if (typeof value === "object" && value !== null && "name" in value) {
console.log((value as { name: string }).name);
}
Unknown and Type Guards
Type guards are the general mechanism for narrowing an unknown value down to something more specific and usable. Common guards include typeof for primitives, instanceof for class instances, and manual property checks for plain objects.
Example: Unknown and Type Guards
function printLength(value: unknown): void {
if (typeof value === "string") {
console.log(value.length);
} else if (Array.isArray(value)) {
console.log(value.length);
}
}
printLength("hello");
Unknown Compared with Any
Both any and unknown can technically store a value of any type, but unknown demands validation before you can do almost anything useful with it, while any lets anything through unchecked. For data coming from an external or untrusted source, unknown is almost always the safer default.
Example: Unknown Compared with Any
let unsafeValue: any = "42";
let safeValue: unknown = "42";
console.log(unsafeValue.toUpperCase()); // allowed, may crash at runtime
// console.log(safeValue.toUpperCase()); // rejected until narrowed
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: