Introduction

The unknown type in TypeScript is a type which we can assign any value of any data type to while still leveraging TypeScript’s type checking. This is different from the any type since the any type bypasses TypeScript’s type checker.

Examples

let aVariable: unknown;

aVariable = 1;
aVariable = "hello";
aVariable = true;
aVariable = {};
aVariable = [1,2,3];

As you can see above, we can assign values of any data type to a variable of type unknown. Let’s see what will happen when we assign a variable of type unknown to a variable with a specific data type:

let aVariable: unknown;

let bVariable: boolean = aVariable; //ERROR
let cVariable: string = aVariable; //ERROR
let dVariable: number = aVariable; //ERROR
let eVariable: object = aVariable; //ERROR
let fVariable: any[] = aVariable; //ERROR
let gVariable: any = aVariable; 
let hVariable: unknown = aVariable;

As you can see a variable of type unknown can only be assigned to another variable that is either of type unknown or any.

Type narrowing

Suppose we have a function parameter called usrs of type unknown and we want to extract a property from that parameter. In order to do that, we have to do a check on that parameter, called narrowing, to extract that property. If we do not, the TypeScript compiler will give us an error since usrs is of type unknown:

function test(usrs: unknown) {
  if (typeof usrs === "object" && usrs && "user" in usrs && typeof usrs.user === "object" && usrs.user && "id" in usrs.user && typeof usrs.user.id === "number") {
    return usrs.user.id;
  }
}

Type assertion

const aString: unknown = "Test";
const bString: string = aString as string;
const cString = bString.split('');

const anotherString: unknown = 1;
const anotherBString: string = anotherString as string;
const anotherCString: string = anotherBString.split(''); //TypeError: anotherBString.split is not a function

In the first example above, we are making the compiler accept that aString can be cast to a string (type assertion). The compiler is not checking whether that is a valid assertion or not. It is trusting that it is what we say it is. Hence, when we use the same method in the second example anotherString, an error will be thrown at runtime.