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 type
is 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
any
typed variable.
- You can also assign
any
typed variable to other type of variables.
- You can assess the properties which do not exist on
any
typed variable.
- You can call
any
typed variable as function, even if it is not a function.
Word of wisdom
Use
any
type 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:
unknown
is thetype-safe
counterpart 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
unknown
typed variable.
-
unknown
typed variable is only assignable tounknown
orany
type.
- You can not perform any operations without narrowing or type assertion.
- Only equality operators are allowed with
unknown
- You cannot create rest from
unknown
type
- Union with
unknown
and other types producesunknown
type with an exception of union withany
which producesany
type
- 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
unknown
before trying to useany
References
Top comments (0)