2023-10-23 ― Tommy Jepsen ✌️
Let's talk about the difference between unknown and any in TypeScript. Something I struggled with when I began writing TypeScript.
There are two places unknown and any differentiate from each other.
Type Safety:
Type Inference:
Here is an example:
let value: unknown;
let anyValue: any;
// These lines will result in type errors
const length = value.length; // Error: Object is of type 'unknown'.
const anyLength = anyValue.length; // No error, even though it might fail at runtime.
// To safely use value, you must perform type checks
if (typeof value === "string") {
const length = value.length; // OK, type is narrowed to string.
}
In summary, as TypeScript developers, using unknown when you're dealing with values of uncertain types is the way to go. It ensures that type safety is upheld through proper type checking. Try to avoid using any unless you have a really compelling reason to do so, as it goes against TypeScript's mission of providing strong typing and type safety - even though it's the easy way out sometimes ;)
My name is Tommy. Im a Product designer and developer from Copenhagen, Denmark.
Connected with me on LinkedIn ✌️