In this tutorial post we are going to discuss about TypeScript Any and unknown types. We will see the difference between these types when it comes in use.
Any DataType
The Any is a additional DataType in TypeScript which is not defined in JavaScript. The following points define the any type:
Example
Assigning any type To Any Type
In the below example we have assigned any type value like number, string and boolean.
let checkany:any;
checkany=1;
checkany="Rohatash";
checkany=true;
Unknown DataType
The Unknown is a additional DataType in TypeScript which is not defined in JavaScript. The following points define the Unknown type:
Example
Assigning Unknown type To Any Type
In the below example we have assigned Unknown type value like number, string and boolean.
//unknown Type
let checkunknown:unknown=10;
let checkanyr:any=checkany; // No error
let checkunknownr1:unknown=checkany; // No error
let checknumber:number=checkunknown; // error
let checkstring:string=checkunknown; // error
Any vs Unknown DataType
SNo. | Any | Unknown |
1 | As the name suggest any means I don't care. | As the name suggest Unknown means I don't know |
2 | It allows assigning any type. | It allows assigning only any and Unknown type. |
3 | It allows calling any method. | It does't allows calling any method. |
4 | Any throws away the type restrictions. | To resolve type restrictions run time error of any type. |
5 | It lead to a run time error. | It check mostly on compile time except any. |