Categories
TypeScript Answers

How to cast a custom type to a primitive type in TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *