Sub topic 4
Changing case with Uppercase, Lowercase, Capitalize, and Uncapitalize
This chapter assumes you can write generic type aliases with extends constraints, and that you know string literal types, unions, and the template literal syntax from the previous chapters. It uses conditional types with infer only in two short examples, and it explains them as they appear.
Template literal types can glue strings together, but they cannot change the case of letters. TypeScript supplies four built-in helper types for that: Uppercase, Lowercase, Capitalize, and Uncapitalize. You will use them whenever a type has to turn "click" into "onClick" or "USER_ID" into "userId".
The four helpers
Each helper takes one string type and returns a new string type.
| Helper | What it does | Example input | Result |
|---|---|---|---|
| `Uppercase<S>` | Converts every character to upper case | `"userName"` | `"USERNAME"` |
| `Lowercase<S>` | Converts every character to lower case | `"userName"` | `"username"` |
| `Capitalize<S>` | Converts only the first character to upper case | `"userName"` | `"UserName"` |
| `Uncapitalize<S>` | Converts only the first character to lower case | `"UserName"` | `"userName"` |
The diagram shows all four applied to the same input.
The same applies in code:
type A = Uppercase<"userName">; // "USERNAME"
type B = Lowercase<"userName">; // "username"
type C = Capitalize<"userName">; // "UserName"
type D = Uncapitalize<"UserName">; // "userName"
type E = Uncapitalize<"userName">; // "userName" (already lower case)Applying a helper to a string that is already in the target form changes nothing. Capitalize and Uncapitalize look only at the first character. They leave the rest of the string alone.
Why these types are "intrinsic"
You cannot write these four helpers with the type features you have seen so far. A conditional type could, in theory, map each letter one at a time, but doing that for the whole Unicode range is impractical. So the compiler implements them directly. If you open TypeScript's lib.es5.d.ts, you find declarations like this:
type Uppercase<S extends string> = intrinsic;
type Lowercase<S extends string> = intrinsic;
type Capitalize<S extends string> = intrinsic;
type Uncapitalize<S extends string> = intrinsic;The word intrinsic means "the compiler provides this". The compiler applies JavaScript's own toUpperCase() and toLowerCase() to the literal text. Two consequences follow:
- The result matches what the same method would return at runtime, so
Uppercase<"ß">follows JavaScript's rules for that character and not any locale-specific rule. - You cannot add a fifth helper of your own, such as one that converts to snake case, as an intrinsic. You compose these four with template literals and
infer, as later sections show.
Distribution over unions
Each helper distributes over a union. It is applied to every member separately, and the results are joined back into a union.
type Method = "get" | "post" | "delete";
type MethodUpper = Uppercase<Method>;
// "GET" | "POST" | "DELETE"
type MethodTitle = Capitalize<Method>;
// "Get" | "Post" | "Delete"This is the property that makes the helpers useful inside template literals. When a placeholder in a template literal type is a union, you get every combination, and a helper inside the placeholder transforms each member before the combination happens.
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickHandler = EventName<"click">;
// "onClick"
type AnyHandler = EventName<"click" | "focus" | "blur">;
// "onClick" | "onFocus" | "onBlur"Capitalize<T> runs first and turns each member into its capitalized form. The template literal then prepends on to each one.
Using a helper on part of a template
A helper takes a whole string type, but you can use it on any part of a template literal type. This lets you change case in one position only.
type Prefix = "user" | "admin";
type Field = "id" | "name";
type ApiKey = `${Prefix}_${Uppercase<Field>}`;
// "user_ID" | "user_NAME" | "admin_ID" | "admin_NAME"
type Method = `${Lowercase<"GET" | "POST">}Request`;
// "getRequest" | "postRequest"You can also nest helpers. The inner one is evaluated first.
type Shout = Uppercase<`${"hello" | "bye"}, world`>;
// "HELLO, WORLD" | "BYE, WORLD"
type Mixed = Uncapitalize<Uppercase<"abc">>;
// "aBC"Uppercase<"abc"> gives "ABC", and Uncapitalize lowers only the first character of that.
Converting between naming conventions
The helpers become powerful once you pair them with infer. A conditional type can split a string at a delimiter, and the helpers then adjust the case of each part. Here is a type that turns snake_case names into camelCase:
type SnakeToCamel<S extends string> =
S extends `${infer Head}_${infer Tail}`
? `${Lowercase<Head>}${Capitalize<SnakeToCamel<Tail>>}`
: Lowercase<S>;
type A = SnakeToCamel<"user_first_name">; // "userFirstName"
type B = SnakeToCamel<"USER_ID">; // "userId"
type C = SnakeToCamel<"name">; // "name"Here is how SnakeToCamel<"USER_ID"> is evaluated:
- The string matches the pattern.
Headis"USER"andTailis"ID". Lowercase<"USER">gives"user".- The recursive call
SnakeToCamel<"ID">does not match the pattern, so it returnsLowercase<"ID">, which is"id". Capitalize<"id">gives"Id".- The pieces join to
"userId".
The reverse direction, from a PascalCase or camelCase name to the form with a lower-case first letter, needs only one helper:
type ToCamel<S extends string> = Uncapitalize<S>;
type X = ToCamel<"UserName">; // "userName"The next chapters cover infer and recursion in more detail. For now, notice the division of labor. infer finds the pieces, and the case helpers reshape them.
Case helpers with mapped types
A mapped type with an as clause can rename every key of an object type. The case helpers are the usual tool for the new names. This chapter shows only a short example, and a later chapter covers key remapping fully.
type ShoutKeys<T> = {
[K in keyof T & string as Uppercase<K>]: T[K];
};
type Config = { host: string; port: number };
type EnvConfig = ShoutKeys<Config>;
// { HOST: string; PORT: number }keyof T & string keeps only the keys that are strings. This matters because Uppercase<K> requires K to extend string, and keyof T can also include number and symbol. Without the & string, the compiler reports that K does not satisfy the constraint.
Case-insensitive comparison
Lowering both sides of a comparison gives you a type-level case-insensitive check:
type SameIgnoringCase<A extends string, B extends string> =
Lowercase<A> extends Lowercase<B> ? true : false;
type T1 = SameIgnoringCase<"Content-Type", "content-type">; // true
type T2 = SameIgnoringCase<"Accept", "Content-Type">; // falseThis works because "content-type" is the lower-case form of both inputs, and two identical literal types are mutually assignable.
Behavior with `string`, empty strings, and non-letters
The helpers do not fail when the input is not a plain literal. They behave in specific ways you should know.
type E1 = Capitalize<"">; // ""
type E2 = Uppercase<"123-abc">; // "123-ABC"
type E3 = Capitalize<"_id">; // "_id" (the first character has no upper-case form)An empty string stays empty. Digits, punctuation, and other characters without a case stay as they are. Capitalize<"_id"> is not "_Id", because the first character is the underscore.
When the input is the wide type string, the compiler cannot compute a literal. It keeps the helper applied to string as a distinct type:
declare const shout: Uppercase<string>;
const ok: Uppercase<string> = "HELLO";
// const bad: Uppercase<string> = "hello"; // Error: "hello" is not in upper case
// const worse: Uppercase<string> = someString; // Error: string is not assignable
const asString: string = shout; // fine: Uppercase<string> is a subtype of stringUppercase<string> means "any string that is already in upper case". A literal like "HELLO" is assignable to it, because upper-casing it changes nothing. A literal like "hello" is not. A plain string value is not assignable either, because the compiler cannot prove it is upper case. This is useful for APIs that must receive an already normalized string.
The runtime side: types do not change values
The helpers act only on types. They never change a value at runtime. If a function converts a string, you write the conversion in JavaScript and then describe the result in the return type.
function capitalize<S extends string>(s: S): Capitalize<S> {
return (s.charAt(0).toUpperCase() + s.slice(1)) as Capitalize<S>;
}
const greeting = capitalize("hello");
const check: "Hello" = greeting; // compiles: the type is "Hello"The as Capitalize<S> cast is needed. Inside the function body, S is a generic type parameter, so TypeScript cannot show that the computed string matches Capitalize<S>. The cast is a promise from you that the implementation and the type agree. If your runtime code and your type disagree, for example if you wrote toLowerCase() here, the compiler will not notice.
Common mistakes
- Expecting
Capitalizeto change every word.Capitalize<"hello world">is"Hello world". Only the first character changes. To capitalize each word you must split the string withinferand rebuild it. - Passing a non-string key.
Uppercase<keyof T>fails whenkeyof Tmay includenumberorsymbol. Intersect withstringfirst, as inkeyof T & string. - Forgetting that unions distribute.
Uppercase<"a" | "b">is"A" | "B", not one string. If you need a single combined string, build it with a template literal, not by transforming a union. - Expecting a literal from
string.Capitalize<string>does not produce"Hello"or any other literal. It stays a wide type, so a mapped type or template that depends on literal keys will lose precision. - Assuming locale-aware behavior. The compiler follows JavaScript's default case mapping. It does not apply rules for a particular language, such as Turkish dotted and dotless
i.
Summary of what to remember
The four helpers are compiler built-ins that work on string types. Uppercase and Lowercase change every character, while Capitalize and Uncapitalize change only the first one. All four distribute over unions, which makes them a natural fit inside template literal placeholders. They never change runtime values, so any function that returns a transformed string needs a runtime implementation and an honest cast.
Exercise
What are the types of A and B?
type A = Capitalize<"hello world">;
type B = ${Uppercase<"a" | "b">}-${Lowercase<"X" | "Y">};
Show answer
A is "Hello world", because Capitalize changes only the first character. B is "A-x" | "A-y" | "B-x" | "B-y". Uppercase distributes over the first union, Lowercase over the second, and the template literal expands every combination of the results.
Exercise
Given SnakeToCamel from this chapter, what is SnakeToCamel<"API_KEY_VALUE">, and why is the first part "api" and not "API"?
Show answer
The result is "apiKeyValue". The first part goes through Lowercase<Head>, so "API" becomes "api". Each later part is lowered by the same type, since the base case returns Lowercase<S>, and then Capitalize makes its first letter upper case: "key" becomes "Key" and "value" becomes "Value". Joined together they give "apiKeyValue".
Exercise
Why does a function with the signature function lower<S extends string>(s: S): Lowercase<S> need as Lowercase<S> on its return statement, and what risk does the cast carry?
Show answer
Inside the function, S is an unresolved type parameter, so TypeScript cannot prove that the result of s.toLowerCase(), which has type string, matches Lowercase<S>. The cast tells the compiler to trust you. The risk is that the compiler does not verify it: if the body does something different, such as calling toUpperCase(), the declared return type would be wrong and no error would appear.