This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Difference Between Any and Unknown DataType


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:

  1. As the name suggest any means I don't care.
  2. It allows assigning any type. so any is the supertype of all the other types.
  3. Any throws away the type restrictions or turn off the type check. So it lead to a run time error.
  4. It allows calling any method.
  5. The TS compiler will allow any operation on values typedany.

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:

  1. As the name suggest Unknown means I don't know.
  2. The unknown type comes into the picture to resolve type restrictions run time error of any type.
  3. It allows assigning only any and Unknown type.
  4. It does't allows calling any method.

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.

Prev Next