Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert number literal type to string literal type

I’ve seen questions about converting string literal types to number types (TypeScript: is there a way to convert a string literal type to a number type?), but not the other way around. Is there a way to define a type type NumberToString<N extends number> such that e.g. NumberToString<42> is 42?

The purpose of this is to provide a return type for Object.keys (in cases where I’m really, really sure that there are no extra properties).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Much much much simpler now with template literal types:

type NumberToString<N extends number> = `${N}`;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading