The ‘unknown‘ type is a type-safe counterpart to the ‘any‘ type in TypeScript. While both types can hold any value, there are important differences in how they can be utilized in your code.
## ‘unknown‘
With the ‘unknown‘ type, TypeScript enforces type-checking to make sure the value assigned to an ‘unknown‘ type is validated before it can be used. To access or use the value of an ‘unknown‘ type variable, you must first use type guards, type assertions, or user-defined type guards to narrow down or assert the specific type you want to work with.
For example, let’s say you have a variable of type ‘unknown‘:
let value: unknown;
If you try to perform any operation on this variable, TypeScript will give you a type error:
let num: number = value + 1; // Error: Object is of type 'unknown'.
You must use a type guard or type assertion to narrow down the type:
if (typeof value === "number") {
let num: number = value + 1; // This is fine now because we checked the type
}
or
let num: number = value as number + 1; // This is fine because we asserted the type
## ‘any‘
On the other hand, the ‘any‘ type can hold any value, like the ‘unknown‘ type, but it also bypasses TypeScript’s type-checking system. This means you can access properties, call methods, or perform any operation on a variable of type ‘any‘ without TypeScript throwing any errors, even if the operation is incorrect.
For example:
let value: any;
value.foo.bar(); // TypeScript won't throw an error
let num: number = value + 1; // TypeScript won't throw an error
## Summary
While both ‘unknown‘ and ‘any‘ types can hold any value, the main difference is how they affect type checking:
- ‘unknown‘ forces you to perform type-checking or type assertions before accessing or using the value. It ensures that the value doesn’t get misused accidentally, which helps maintain type safety in your code.
- ‘any‘ bypasses the type-checking system, allowing you to access or use the value without any restrictions. It could potentially lead to errors at runtime due to incorrect usage.
In most cases, you should prefer using ‘unknown‘ over ‘any‘ to maintain type safety in your TypeScript code.