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
.
const unknownType: unknown = "123"const cast1: number = <number>unknownType;const cast2: number = unknownType as number;
Casting constraints
If you try to cast to a string
directly without using an unknown type, TypeScript will warn that there are not sufficient overlaps. The TypeScript transpiler gives the solution: casting to ...