TypeScript Reference ยท Primitive and Special Types
TypeScript Uppercase, Lowercase, Capitalize, Uncapitalize
Reference for TypeScript's intrinsic string types Uppercase, Lowercase, Capitalize and Uncapitalize: how they transform literal types and where to use them.
TypeScript ships four intrinsic string types that transform string literal types: Uppercase<S>, Lowercase<S>, Capitalize<S> and Uncapitalize<S>. They are called intrinsic because the compiler implements them directly; you cannot write them with ordinary type operators.
They work on literal types and unions of literals, and on template literal types. They only change the type, not a value: to change a real string at runtime you still call toUpperCase() and friends, and then you may need a cast so the type matches.
type Up = Uppercase<"hello">; // "HELLO" type Cap = Capitalize<"hello">; // "Hello"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type Uppercase<S extends string> type Lowercase<S extends string> type Capitalize<S extends string> type Uncapitalize<S extends string>
| Type | Effect |
|---|---|
Uppercase<S> |
Converts every character of S to upper case. |
Lowercase<S> |
Converts every character of S to lower case. |
Capitalize<S> |
Upper-cases the first character only. |
Uncapitalize<S> |
Lower-cases the first character only. |
Edge cases:
- They distribute over unions:
Uppercase<"a" | "b">is"A" | "B". Uppercase<string>is notstring; it is a special type meaning "a string that is already upper case", and it is assignable tostringbut not the reverse.Capitalize<"">is"".- The transformation follows the JavaScript
toUpperCase/toLowerCaserules of the compiler's runtime, not locale rules.
Usage notes
- Pair with template literal types.
`get${Capitalize<K>}`builds method names in mapped types withasremapping. See template literal types. - Constrain keys. In a mapped type over
keyof T, add& stringbefore using these types, because keys may also benumberorsymbol. - Runtime still needed. The types never change a value. A function returning
Uppercase<S>needs a real conversion plus a cast. - Case conversion is shallow. There is no built-in
CamelCaseorSnakeCase; you build them recursively with template literal types. - Not for enums or non-strings. The parameter must extend
string. - Version. Available since TypeScript 4.1 together with template literal types.