Function Parameters: unknown vs any
What you'll learn: Why using unknown instead of any for function parameters makes your code safer when accepting values from external sources like user input or API responses.
The Safety Problem with any Parameters
When you declare a function parameter as any, TypeScript turns off all type checking for that value. This means you can call any method, access any property, or perform any operation on it without errors — even operations that will crash at runtime:
function processData(input: any) {
// TypeScript allows all of this without complaint:
input.toUpperCase(); // What if input is a number?
input.length; // What if input has no length?
input.nonexistent.method(); // What if this doesn't exist?
return input * 2; // What if input is an object?
}
All these operations compile successfully, but many will fail at runtime with mysterious errors.
Why unknown Is Safer for External Data
Think of unknown as a locked box: you know something is inside, but you must inspect it before using it. This matches reality when accepting data from external sources — you don't actually know what you're getting until you check.
function processData(input: unknown) {
// TypeScript REQUIRES you to narrow the type first:
if (typeof input === "string") {
return input.toUpperCase(); // ✓ Safe: we know it's a string
}
if (typeof input === "number") {
return input * 2; // ✓ Safe: we know it's a number
}
throw new Error("Unexpected input type");
}
With unknown, TypeScript forces you to write defensive code that validates data before using it — exactly what you should do with untrusted input anyway.
The Right Tool for the Job
Use unknown for parameters that accept arbitrary external values (JSON parsing, form submissions, API responses). Reserve any only for rare cases where you explicitly want to opt out of type checking entirely.
Key Takeaway: unknown parameters force you to validate data before using it, catching bugs that any would let slip through into production — making it the safer choice for functions that accept values from external, untrusted sources.