Enforce String Casing in TypeScript: Creating Uppercase, Lowercase, and Capitalized String Types
Jun 23, 2023 · 2 min readIn 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.
Uppercase
This utility type converts each character in the string to the uppercase version.
Lowercase
This utility type converts each character in the string to the lowercase version.
Capitalize
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 string
type.
Back to our original example, we can implement IsUppercase
type this way:
and the str
will error when passed lowercase string
The same idea apply for both IsLowercase
and IsCapitalized
too.
Wrap Up
That’s it for the article, hope you find this little trick useful.