Sometimes, we want to cast a custom type to a primitive type in TypeScript.
In this article, we’ll look at how to cast a custom type to a primitive type in TypeScript.
How to cast a custom type to a primitive type in TypeScript?
To cast a custom type to a primitive type in TypeScript, we can assign our value to a variable with the type we want.
For instance, we write
type Rating = 0 | 1 | 2 | 3 | 4 | 5;
const myRating: Rating = 4;
const rate: number = myRating;
to assign myRating
to the rate
variable which is a number
.
Then we can use rate
as a number without errors.
Conclusion
To cast a custom type to a primitive type in TypeScript, we can assign our value to a variable with the type we want.