Search⌘ K

Unknown: A Better any

Explore the unknown type in TypeScript and understand how it offers safer alternatives to the any type. Learn how to manage variables with unknown types, use type assertions cautiously, and apply optional chaining and nullish coalescing introduced in TypeScript 3.7 to handle null or undefined values efficiently.

We'll cover the following...

The unknown type is half a specific explicit type and half the type any which allows everything. Declaring a variable as unknown allows us to set a wide variety of types without allowing unwanted access to properties or the value of a type. The following code demonstrates that a variable with type any can be assigned a string and then used with a function of the string type.

Later, the variable is assigned to a number that does not have substr function. However, TypeScript does not catch an attempt to invoke a function that does not exist.

TypeScript 3.3.4
let variable1: any;
variable1 = "It is a string";
console.log(variable1.substr(0,2)) // Output "it"
variable1 = 1;
console.log(variable1.substr(0,2)) // Crash

Changing ...