Apart from the primitive types i.e. string, number, boolean ,null and undefined, there are two special types in TypeScript :
- Any
- Unknown
Most of us are familiar with any type because that is the first thing we commonly use when we could not find a type or we feel lazy to write the type for a big and complex object.
For those who are seeing this first time. Here is a short brief on any:
Any
If you want to avoid type checking and you do not want typescript to complain about it you can simply use any type. As the name suggests, any accepts all the types. It is also known as top type.
The
top typeis sometimes called also universal type, or universal supertype as all other types in the type system of interest are subtypes of it.
Syntax
Implications of assigning any type
- You can assign anything to
anytyped variable.
- You can also assign
anytyped variable to other type of variables.
- You can assess the properties which do not exist on
anytyped variable.
- You can call
anytyped variable as function, even if it is not a function.
Word of wisdom
Use
anytype as last resort because it takes away all the power that is provided by typescript
Enter the world of unknown
unknown type is first introduced in Typescript 3.0. It is also another top type in Typescript. As per official docs:
unknownis thetype-safecounterpart ofany
It is similar to any because it can accept all types of values. It enforces a bit more restriction than any because you cannot perform any action on unknown typed variable without type assertion or narrowing it to more specific type.
Syntax
Implications of assigning unknown type
- You can assign anything to
unknowntyped variable.
-
unknowntyped variable is only assignable tounknownoranytype.
- You can not perform any operations without narrowing or type assertion.
- Only equality operators are allowed with
unknown
- You cannot create rest from
unknowntype
- Union with
unknownand other types producesunknowntype with an exception of union withanywhich producesanytype
- When taking Intersection with
unknown, it is absorbed by other types.
Perform operation on unknown type
Before performing any operation on unknown type we need to narrow it down using typeof or instanceof operator. We can also use type assertions with as or we can provide a custom function which acts as type guard
Using typeof
Using instanceof
Using type assertion
Example
LocalStorage
Following is an example of saving data into localStoarage. As anything can be saved in localStorage that's why the type of data is unknown.
Params to a http request
Word of wisdom
Use
unknownbefore trying to useany
References


















Top comments (0)