Search⌘ K

Casting to Change Type

Explore how to change variable types safely in TypeScript through casting. Understand the difference between the two casting forms and the risks involved when casting mismatched types. Learn best practices for casting, such as limiting casts to strategic points like untyped data handling, to maintain code stability and type integrity.

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 ...