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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.