Sub topic 4
Changing Case in TypeScript String Types
This chapter assumes you know basic TypeScript type aliases, string literal types, union types, generics, and mapped types. It focuses on the four built-in string manipulation types: Uppercase, Lowercase, Capitalize, and Uncapitalize.
These utilities change a string literal type at compile time. They do not change a string value while the program runs.
The four intrinsic string types
TypeScript provides four intrinsic string manipulation types:
| Utility | What it changes | Example |
|---|---|---|
| `Uppercase<S>` | Every character to uppercase | `Uppercase<"save">` becomes `"SAVE"` |
| `Lowercase<S>` | Every character to lowercase | `Lowercase<"SAVE">` becomes `"save"` |
| `Capitalize<S>` | The first character to uppercase | `Capitalize<"save">` becomes `"Save"` |
| `Uncapitalize<S>` | The first character to lowercase | `Uncapitalize<"Save">` becomes `"save"` |
The input must be a string type. A string literal gives the most precise result. A broad string type usually produces string, because the compiler does not know the actual characters.
type Loud = Uppercase<"warning">;
type Quiet = Lowercase<"WARNING">;
type Title = Capitalize<"warning">;
type Normal = Uncapitalize<"Warning">;
const loud: Loud = "WARNING";
const quiet: Quiet = "warning";
const title: Title = "Warning";
const normal: Normal = "warning";These types describe allowed values. They do not convert values:
function toUpperCaseAtRuntime(value: string): string {
return value.toUpperCase();
}
const result = toUpperCaseAtRuntime("warning");
// result has type string, not "WARNING"The runtime method and the type utility solve different problems. The method changes data. The utility checks the shape of data known to the compiler.
Applying transformations to unions
String manipulation types distribute over unions. In other words, TypeScript transforms each member separately and creates a new union.
type Event = "click" | "focus" | "blur";
type EventName = Capitalize<Event>;
// "Click" | "Focus" | "Blur"
const eventName: EventName = "Click";This behavior works well with template literal types. You can transform a part and then place it into a larger string pattern.
type EventHandlerName<T extends string> = `on${Capitalize<T>}`;
type HandlerName = EventHandlerName<"click" | "focus">;
// "onClick" | "onFocus"
const clickHandler: HandlerName = "onClick";
const focusHandler: HandlerName = "onFocus";The constraint T extends string says that callers can provide only string types. Without that constraint, Capitalize<T> would be invalid because Capitalize expects a string-like input.
Transforming keys in a mapped type
A mapped type can use an as clause to calculate new property names. Combining key remapping with Capitalize lets you generate method names from object properties.
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type Person = {
name: string;
age: number;
};
type PersonGetters = Getters<Person>;
const getters: PersonGetters = {
getName: () => "Ada",
getAge: () => 36,
};keyof T & string keeps only string keys. That matters because object keys can also be numbers or symbols, while Capitalize works with strings.
The mapped type processes the keys as follows:
Combining multiple transformations
You can nest the utilities when a naming convention requires more than one operation.
type ConstantName<T extends string> = Uppercase<T>;
type SetterName<T extends string> = `set${Capitalize<T>}`;
type LowerEventName<T extends string> = Lowercase<T>;
type Constant = ConstantName<"maxRetries">;
// "MAXRETRIES"
type Setter = SetterName<"timeout">;
// "setTimeout"
type LowerEvent = LowerEventName<"CLICK">;
// "click"For a string containing several words, Capitalize still changes only the first character:
type Method = `get${Capitalize<"user name">}`;
// "getUser name"It does not convert "user name" to "UserName". Converting separators and capitalizing every word requires a more advanced recursive type or a runtime function.
Common errors
Expecting runtime conversion
This code does not make a variable uppercase:
let command: Uppercase<"start"> = "START";
// command = "start"; // Compile-time errorThe type restricts the value. It does not call toUpperCase().
Passing a broad string
type AnyUppercase = Uppercase<string>;
// stringThe compiler cannot preserve a particular uppercase result when the input could be any string. Use literal types or constrained generic values when you need precise results.
Forgetting key constraints
This definition is invalid because keyof T may include number or symbol:
// type BadGetters<T> = {
// [K in keyof T as `get${Capitalize<K>}`]: () => T[K];
// };Use keyof T & string when a key is passed to a string manipulation utility.
Exercise
What is the resulting type of EventHandlerName<"change" | "submit">, and why?
Show answer
It is "onChange" | "onSubmit". The generic type distributes Capitalize over the union, then prefixes each transformed member with "on".