Unknown

In a similar vein to never, TypeScript 3 introduces a type named unknown. The unknown type can be seen as a type-safe equivalent of the type any. In other words, before we use a variable that has been marked as unknown, we must explicitly cast it to a known type. Let's explore the similarities between unknown and any, as follows:

let unknownType: unknown = "an unknown string"; 
console.log(`unknownType : ${unknownType}`); 
 
unknownType = 1; 
console.log(`unknownType : ${unknownType}`); 

Here, we have defined a variable named unknownType, and assigned a string value to it. We then log its value to the console. Note that we have also explicitly typed this variable to be of type unknown.

We then assign a numeric value of 1 to the unknownType variable, and again log its value to the console. The type behavior of this variable is the same as any, in that we can reassign its type on the fly. The output of this code is as follows:

unknownType : an unknown string
unknownType : 1

As we can see from the output, the value of the unknownType variable has changed from a string to a number, similar to the any type.

If, however, we attempt to assign the unknownType variable to a known type, we start to see the difference between any and unknown, as follows:

let numberType: number; 
numberType = unknownType; 

Here, we have a variable named numberType, which is of type number, and we are attempting to assign the value of unknownType to it. This will generate the following error:

error TS2322: Type 'unknown' is not assignable to type 'number'  

To fix this error, we will need to explicitly cast the unknownType variable to a number type as follows:

numberType = <number>unknownType; 

Note the explicit cast on the right-hand side of the assignment operator, <number>unknownType. This code compiles without error.

Again, the unknown type is seen as a type-safe version of the any type, as we are forced to explicitly cast from an unknown type to a known type before we make use of a variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.133.228