Course contentsShow
← TypeScript
Lesson 940 of 1,79621. The unknown TypeFree lesson

unknown vs any in Function Parameters

When a function truly accepts anything, unknown is safer than any since it forces the implementer to narrow inside.

unknown vs any in Function Parameters

You'll learn: Why choosing unknown over any for function parameters makes your code safer by forcing you to validate inputs before use.


The Core Idea

When writing a function that accepts "anything," you have two choices: any or unknown. While both accept any value, they behave very differently inside the function body.

With any: TypeScript turns off type checking. You can do whatever you want with the parameter, and TypeScript won't complain. This means bugs slip through.

With unknown: TypeScript forces you to prove what type the value is before you use it. You must narrow the type using guards, predicates, or checks. This catches errors at compile time.

Plain English Analogy

Think of any as accepting a mystery package and immediately opening it without checking what's inside. You might get what you expect, or you might get a mess.

unknown is like accepting the same package but being required to inspect it first—shake it, read the label, verify the contents—before you're allowed to use what's inside. More work upfront, but no surprises.

When This Matters

Any function that accepts data from outside your codebase—user input, API responses, file parsing—should prefer unknown parameters. The implementer (you or your teammate) must write validation logic, which is exactly what you want for untrusted data.

Using any in these cases creates a false sense of safety. The function compiles, but runtime errors wait in production.

Key Takeaway: When a function truly accepts anything, use unknown parameters instead of any—it forces safe narrowing inside the function and prevents accidental misuse of unvalidated data.