Basic Operations on unknown Values
You'll learn: what you're allowed (and not allowed) to do with an unknown value before narrowing it to something more specific.
When TypeScript gives you a value typed as unknown, it's like receiving a locked box: you know there's something inside, but TypeScript won't let you use it until you prove what it contains. This is the key safety feature that makes unknown vastly superior to any.
What You Cannot Do
Almost nothing! Unlike any, you cannot:
- Access properties (even common ones like
.length) - Call it as a function
- Perform arithmetic operations
- Use it with most operators
- Assign it to variables of specific types
let value: unknown = "hello";
// ❌ All of these will cause errors:
// value.toUpperCase();
// value + " world";
// value();
// let str: string = value;
TypeScript forces you to verify the type first through narrowing (which you've already learned).
What You CAN Do
The operations allowed on unknown without narrowing are extremely limited:
- Assign to
anyorunknown— these are the only types that accept anything - Use equality operators —
===,!==,==,!= - Use
typeof,instanceof, orin— these are your narrowing tools - Type assertions (though this defeats the safety purpose)
let value: unknown = 42;
// ✅ These are safe:
let another: unknown = value; // unknown accepts unknown
let anything: any = value; // any accepts everything
if (value === 42) {
// Comparison works
}
if (typeof value === "string") {
// Now you can use string methods
value.toUpperCase();
}
Think of unknown as a "prove-it-first" type: it acknowledges that a value exists but demands evidence before granting access.
Key Takeaway: unknown values support almost no operations directly—you must narrow them first using type guards like typeof, instanceof, or equality checks before TypeScript allows meaningful interaction.