Any, Unknown and Never
On this page we want to take a closer look at the three TypeScript types any
,
unknown
and never
. We will discuss their differences and when its best to
use which.
Any
If you've used TypeScript for a while you most certainly stumpled apon the any
type or maybe even have used it 😈.
Put simply the any
type disables the typechecking so every possible value is
valid.
Regarding Set theory the any
type is the only type that doesn't really fit in.
One might assume that any
is the type that contains all types. This however is
not the case since we are allowed to call e.g. toFixed
on an any
type. This
function doesn't exist on string
and other types though.
const str: any = 'Hello World!';
// Works perfectly fine
str.toFixed();
When to use?
It can be helpful when you create your typedefinitions and haven't created every
type yet. Then you can use any
as a placeholder which you then replace at a
later point once the types have been created.
In every other case using any
is not adviced since it loosens your typesafety
which can / will result in bugs being created. If you feel like using any
you
probably should use unknown
instead.
Unknown
At first glance the unknown
type looks similar to the any
type. However, the
unknown
type doesn't disable typechecking and fits into Set theory.
The unknown
type is the type that contains all types.
const str: unknown = 'Hello World!';
// Errors because not all types have a 'toFixed' function
str.toFixed();
// Errors because not all types have a 'includes' function
str.includes('Hello');
To be able to use any method on str
we first need to check its proper type:
const str: unknown = 'Hello World!';
if (typeof str === 'string') {
// Works as expected
str.includes('Hello');
// ^? const str: string
}
When to use
One should use the unknown
type whenever you don't know the exact type or when
you feel like using any
. This is due to the fact that you are forced to check
the type and properly and only are able to call functions or access properties
when you can be certain that they exist.
Never
Last but not least the never
type. It can be describe as the type that can't
be created or simply nothing.
In regards to Set theory it represents the empty set.
When to use
There are very rare usecases when you would need to use the never
type. Its
rather a type you might see TypeScript resolve to in some cases. An example
where you would explicitly use the never
type would be an
exhaustive switch.