Google News
logo
TypeScript - Interview Questions
What is an unknown type, and when to use it in TypeScript?
The unknown type is the type-safe counterpart of any type. You can assign anything to the unknown, but the unknown isn’t assignable to anything but itself and any, without performing a type assertion of a control-flow-based narrowing. You cannot perform any operations on a variable of an unknown type without first asserting or narrowing it to a more specific type.
 
Consider the following example. We create the foo variable of unknown type and assign a string value to it. If we try to assign that unknown variable to a string variable bar, the compiler gives an error.
let foo: unknown = "Chanti";
let bar: string = foo; // Type 'unknown' is not assignable to type 'string'.(2322)
You can narrow down a variable of an unknown type to something specific by doing typeof checks or comparison checks or using type guards. For example, we can get rid of the above error by
let foo: unknown = "Chanti";
let bar: string = foo as string;
Advertisement