TypeScript: The Difference Between "any" and "unknown" Types
This short article will look at the differences between any
and unknown
types in TypeScript.
The "any" type
As its name implies, the any
type can represent "any" value in TypeScript.
It is incredibly flexible, but you essentially opt out of TypeScript's type-checking mechanism.
With any
, you can perform any operation (like calling a method or accessing a property), and assign it to any other type, and TypeScript wouldn't raise a single type error.
As an example:
const profile: any = { firstName: "Niall", }; // No error even though lastName does not exist. Compiles successfully. 🙀 console.log(profile.lastName);
This is usually a major "NOPE" since we want good types in TypeScript. 😉 By skipping type checking, you might accidentally introduce type errors that TypeScript can't catch.
The "unknown" type
unknown
is similar to any
in that it can contain any value, but unknown
is type-safe.
How?
TypeScript forces you to perform a type check before operating on unknown
variables. You can't accidentally misuse the value because TypeScript will require you to verify with the compiler what type the value is before you can use it.
Let's look at an example similar to our last one:
const profile: unknown = { firstName: "Niall", }; // ❌ ERROR! Because TypeScript doesn't know what type `profile` is. console.log(profile.firstName);
And if we wanted to make it work it takes a little extra work:
const profile: unknown = { firstName: "Niall", }; if (typeof profile === "object" && profile !== null) { if ("firstName" in profile) { // ✅ We have confirmed the type sufficiently before compile time! console.log(profile.firstName); } }
Although it takes a bit more work, using unknown
maintains type safety, making it the better option when unsure of a variable's type.
Happy coding! ✨
Follow me on Twitter or connect on LinkedIn.
🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉