The unknown type in TypeScript

Hi in this post we are going to see how the “unknown” type works in TypeScript.

For the few cases where we have a value whose type we really don’t know ahead of time, don’t use any, and instead use “unknown” type. Like “any” type represent any value, but TypeScript won’t let you use an “unknown” type until you refine it by checking what it is.

What operations does “unknown” type support?

We can compare “unknown” values with ==, ===, ||, && and ?, also we can negate them with !, and refine them with Javascript’s typeof and instanceof operators.

Examples:

let age: unknown = 31; // age unknown type

let a = age === 1; // a is boolean type, because === is permited

let b = age + 10; // Error: Object is of type 'unknown'.t -> because "+"" operator is not permited to sum "unknown" values

// at this point age is unknown type
if (typeof age === "number") {
  // When we use typeof the age is being "refine"
  // age take the number type
  let c = age + 10; // c is number type, this is why we can sum "number" types whithout problems
}

View of the same code, see how TypeScript detect an error on age variable:

By Cristina Rojas.