DEV Community

Cover image for From any to unknown: A Guide to Upgrading Your TypeScript Typing
AILI Fida Aliotti Christino
AILI Fida Aliotti Christino

Posted on • Edited on

From any to unknown: A Guide to Upgrading Your TypeScript Typing

In TypeScript, the unknown type is used to represent values that are not known at compile time. This is in contrast to the any type, which represents values that can be of any type, including values that are not known at compile time.

One advantage of using unknown over any is that it provides a level of type safety. When a value is of type unknown, the TypeScript compiler will require the programmer to perform type checks before performing certain operations on that value. This helps to prevent unintended type errors at runtime.

For example, consider the following code:

function printLength(x: any) {
  console.log(x.length);
}

printLength("hello"); // Output: 5
printLength([1, 2, 3]); // Output: 3
printLength({ key: "value" }); // Output: undefined

Enter fullscreen mode Exit fullscreen mode

In this code, the printLength function takes a value of type any and attempts to access the length property on that value. However, not all values have a length property, so this code will produce an error when passed an object like:

{ key: "value" }
Enter fullscreen mode Exit fullscreen mode

If we change the type of the parameter x to unknown, the TypeScript compiler will require us to perform a type check before accessing the length property:

function printLength(x: unknown) {
  if (typeof x === "string" || Array.isArray(x)) {
    console.log(x.length);
  } else {
    console.log("Cannot determine length");
  }
}

printLength("hello"); // Output: 5
printLength([1, 2, 3]); // Output: 3
printLength({ key: "value" }); // Output: Cannot determine length
Enter fullscreen mode Exit fullscreen mode

In this revised version of the printLength function, we perform a type check using the typeof operator and the Array.isArray() function before attempting to access the length property. This ensures that the code will only attempt to access the length property on values that are known to have it, and will handle other values gracefully.

Another advantage of using unknown over any is that it forces the programmer to be explicit about the type of a value. This can make the code easier to understand and maintain, as it clearly communicates the programmer's intentions and assumptions about the types of values being used.

In summary, the unknown type is a useful tool in TypeScript for representing values that are not known at compile time, and provides a level of type safety and explicitness that is not available with the any type. It is often a good idea to use unknown instead of any whenever possible in order to make the code more robust and maintainable.

Buy Me A Coffee

Top comments (1)

Collapse
 
nichiren96 profile image
Roel Tombozafy

Thanks for sharing!