Typescript’s type assertion features help us to override type inference and indicate a specific type to a variable.
Type assertion may not be the most common of the features you employ, but it is invaluable when you are migrating from Javascript. Or, when you have to interact with Javascript libraries or data from external systems in your Typescript code.
Take note of one important thing though - since all Typescript code is compiled to Javascript, any and all assertion is applied at compile time. There is no runtime type assertion.
So, how do you type assert anything?
Type assertion for simple variables
Consider this very simple example -
|
|
In the normal course of time, you end up treating one
as a number.
|
|
But, what if you want to promote one
to a string? This is where assertion plays a part - you can tell Typescript to treat one
as a string rather than infer it as a number.
|
|
realOne
is a string representation of the any
typed one
. It can lend itself well to string operations as expected.
|
|
You could also do the same assertion using an alternate syntax. Use one as
instead of <>
syntax.
|
|
Type assertion in objects
Let’s take a look at a recently used example -
|
|
As seen in another post planet
is treated as a variable with type {}
and therefore, planet.name
will throw an error.
We can solve this problem by manually inferring the type.
|
|