Casting to Change Type
In this lesson, you will see how to move from one type to another.
We'll cover the following
How do we cast? #
TypeScript can cast using two different forms: <> or as
. The former is not recommended because it conflicts with the JSX/TSX format which is now becoming popular because of React. The latter is just as good, and it works in all situations.
The first way is to use the symbols <
and >
with the type desired in between. This syntax requires the cast before the variable that you want to coerce.
The second way is to use the keyword as
. as
is placed after the variable you want to cast and followed by the type you want to cast.
The following code demonstrates an unknown
type cast to a number
.
Get hands-on with 1200+ tech skills courses.