Introduction


If you are familiar with TypeScript, you know that its main advantages are:

  • typing (obviously!)
  • availability of last JavaScript features without worrying of browsers compatibility
  • easy reading and navigating in the code in major text editors


Typing is nevertheless optional in TypeScript, and also comes with the any type, which basically allows to assign whatever type to the variable. We can assume that an over-use of any type will result in a less robust and less sustainable code.


TypeScript 3.0 (July 2018) introduced a new type: unknown.


Definition


The unknown type is the "secure" alterative of any. Any type can be assigned to unknown, but unknown can only be assigned to itself and any.

// Anything is assignable to unknown
function myFirstFunction(value: any) {
 let x: unknown;
 x = 123;
 x = "hello";
 x = [1, 2, 3];
}

// unknown assignable only to itself and any
function mySecondFunction(x: unknown) {
 let v1: any = x; // ok
 let v2: unknown = x; // ok 
 let v3: string = x; // Error
}


We must restrict to a more specific type before using it.


Examples: Checking types


For instance, we can use unknown is a function that will check the type of the argument:

function isArray(x: unknown): boolean {
 return Array.isArray(x);
}


We can also use it in a function that accepts a value which we don't know the type, and that returns a different string according to the actual type.

function printType(x: unknown): string {
 if (typeof x === "string") {
  return `${x} is a string`;
 }
 if (typeof x === "number") {
  return `${x} is a number`;
 } 
 return `${x} is not a string nor a number`;
}


Conclusion


In some cases, it can be interesting to use the unknown type, especially to avoid the any type. It allows less flexibility and therefore more robustness.