In this post, I’ll share a little trick to create type that only allow uppercase, lowercase, or capitalized string in Typescript using intrinsic string manipulation types in Typescript.
What we want to achieve:
Intrinsic String Manipulation Types
Before showing the solution, I would like to introduce you to Intrinsic String Manipulation Types that’re built into Typescript itself.
This utility type converts each character in the string to the uppercase version.
This utility type converts each character in the string to the lowercase version.
This utility converts only the first character in the string to uppercase.
Enforcing String Casing
Now, an interesting use case for those helper function is to enforce casing for the
Back to our original example, we can implement
IsUppercase type this way:
str will error when passed lowercase string
The same idea apply for both
That’s it for the article, hope you find this little trick useful.