Casting to Change Type
In this lesson, we will learn how to cast values from one type to another.
Two ways to cast
TypeScript casts use two different forms: <>
or as
. The former enters into conflict with the JSX/TSX format which is now getting popular because of React, hence it is not recommended.
const cast1: number = <number>1;
The latter is as good and it works in all situations.
const cast2: number = 1 as number;
The first way is to use the symbols <
and >
with the type desired in-between. The syntax requires the cast before the variable that we want to coerce.
The second way is to use the keyword as
. as
is placed after the variable we want to cast followed by the type to cast.
The danger of casting
Casting is a delicate subject since you can cast every variable into something without completely respecting the contract into which you cast. For ...