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:
const str: IsUppercase = "hello"; // we want this line to error
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.
type Greeting = "Hello, world";type ShoutyGreeting = Uppercase<Greeting>; // type ShoutyGreeting = "HELLO, WORLD"
Lowercase
This utility type converts each character in the string to the lowercase version.
type Greeting = "Hello, world";type ListlessGreeting = Lowercase<Greeting>; // type ListlessGreeting = "hello, world"
Capitalize
This utility converts only the first character in the string to uppercase.
type Greeting = "hello, world";type CapitalizedGreeting = Capitalize<Greeting>; // type CapitalizedGreeting = "Hello, world"
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:
type IsUppercase = Uppercase<string>;
and the str
will error when passed lowercase string
const a: IsUppercase = "aa"; // Type 'string' is not assignable to type 'Uppercase<string>'const a2: IsUppercase = "AA"; // OK
The same idea apply for both IsLowercase
and IsCapitalized
too.
type IsLowercase = Lowercase<string>;type IsCapitalized = Capitalize<string>;
const b: IsLowercase = "bB"; // Type 'string' is not assignable to type 'Lowercase<string>'const b2: IsLowercase = "bb"; // OK
const c: IsCapitalized = "cC"; // Type 'string' is not assignable to type 'Capitalize<string>'const c2: IsCapitalized = "Cc"; //OK
Wrap Up
That’s it for the article, hope you find this little trick useful.