TypeScript's any vs. unknown: Discover how any offers flexibility at the cost of type safety, while unknown enforces stricter checks, ensuring safer code practices.
Apart from the primitive types i.e. string
, number
, boolean
,null
and undefined
, there are two special types in TypeScript :
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
:
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
any
typed variable.any
typed variable to other type of variables.any
typed variable.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
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
unknown
typed variable.unknown
typed variable is only assignable to unknown
or any
type.unknown
unknown
typeunknown
and other types produces unknown
type with an exception of union with any
which produces any
typeunknown
, 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
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