Executando verificação de segurança...
-9

Difference between "any" and "unknown" Typescript

Have you ever wondered what the difference is between any and unknown in TypeScript? And why they are so similar, theoretically accepting any type of data.

If you've had this doubt, let me clarify it for you.

Any vs Unknown

In TypeScript, unknown and any are types that allow flexible usage regarding the type of data a variable can store; however, they have important differences:

any:

  • Is the most flexible type in TypeScript.
  • A variable of type any can store any type of data, and TypeScript does not perform type checking or offer IntelliSense for these variables.
  • It's useful when migrating existing code to TypeScript or when the exact type is unknown or irrelevant to the context.

unknown:

  • Is more restrictive than any.
  • A variable of type unknown can also store any type of data, but you must perform a type check before using it safely.
  • TypeScript requires you to perform a type check (like typeof, instanceof, or comparisons) before you can safely operate on variables of type unknown.
  • It's useful when you want to ensure that the type is verified before using it, adding a layer of security compared to using any.

Examples of usage:

Using any:

1 let usingAny: any;
2 
3 usingAny = 10;
4 console.log(usingAny.toFixed(2));
5 
6 usingAny = "Hello TypeScript";
7 console.log(usingAny.toUpperCase());

In this example, the variable usingAny can store any type of data without restrictions. There's no type checking, so toFixed() and toUpperCase() are called directly, regardless of the current type of usingAny.

Using unknown:

1 let usingUnknown: unknown;
2 
3 usingUnknown = 10;
4 console.log(usingUnknown.toFixed(2)); // Error: Object is of type 'unknown'
5 
6 usingUnknown = "Hello TypeScript";
7 if (typeof usingUnknown === 'string') {
8     console.log(usingUnknown.toUpperCase());
9 }

In this example, the variable usingUnknown can store any type of data, but TypeScript doesn't allow accessing properties or methods directly without first checking the type. For the string case, a type check (typeof) is necessary before using toUpperCase(), ensuring TypeScript knows that usingUnknown is indeed a string before attempting to call toUpperCase().

Final Considerations

any is less secure because it allows any type without restrictions or checks.

unknown is safer because it requires a type check before it can be used safely.

In conclusion, if possible, avoiding any in favor of unknown and performing a type check before usage is generally a better practice to ensure security and clarity in TypeScript code.