TypeScript String Case Types
The string case utilities transform literal string types at the type level. Uppercase, Lowercase, Capitalize and Uncapitalize each rewrite every literal in a union.
Uppercase builds shouted constants
Uppercase rewrites every literal in the union. Variables of the new type accept only the shouted spellings.
type LevelName = 'low' | 'high';
type ShoutedLevel = Uppercase<LevelName>;
const first: ShoutedLevel = 'LOW';
const second: ShoutedLevel = 'HIGH';
console.log(first);
console.log(second);Lowercase and Uncapitalize reverse the case
Lowercase rewrites the whole literal. Uncapitalize touches only the first letter.
type ShoutName = 'ALERT' | 'MUTE';
type QuietName = Lowercase<ShoutName>;
type FieldName = Uncapitalize<'Title' | 'Price'>;
const quiet: QuietName = 'alert';
const field: FieldName = 'title';
console.log(quiet);
console.log(field);Capitalize builds getter names
Capitalize turns a field name into the second half of a getter name. The template joins the prefix and the capitalized field.
type FieldName = 'title' | 'price';
type GetterName = `get${Capitalize<FieldName>}`;
const firstGetter: GetterName = 'getTitle';
const secondGetter: GetterName = 'getPrice';
console.log(firstGetter);
console.log(secondGetter);Capitalize inside a mapped key remap
A mapped type can rename each key while it builds a new shape. Here each book field becomes a getter that returns the field type.
interface Book {
title: string;
pages: number;
}
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type BookGetters = Getters<Book>;
const getters: BookGetters = {
getTitle: () => 'Dune',
getPages: () => 412,
};
console.log(getters.getTitle());
console.log(getters.getPages());Example
type VerbName = 'SAVE' | 'LOAD';
type CommandName = Lowercase<VerbName>;
type ButtonLabel = Capitalize<CommandName>;
const saveLabel: ButtonLabel = 'Save';
const loadLabel: ButtonLabel = 'Load';
console.log(saveLabel);
console.log(loadLabel);Key points
- Uppercase<T> converts each string literal in T to upper case.
- Lowercase<T> converts each string literal in T to lower case.
- Capitalize<T> uppercases the first letter of each literal and keeps the rest unchanged.
- Uncapitalize<T> lowercases the first letter of each literal.
- The case utilities change types only, and runtime strings keep the case they were written with.
- A case utility can sit inside a mapped type, so key names transform while the type is built.
In this example, Lowercase first turns the shouted verbs into command names, and Capitalize then builds the label type from those names.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What literal type does Capitalize<'price'> produce?