TypeScript Reference ยท Utility Types
TypeScript Capitalize<S> utility type
Reference for Capitalize<S> in TypeScript: an intrinsic type that upper-cases only the first character of a string type, ideal for getter and handler names.
Capitalize<S> converts the first character of a string literal type to upper case and leaves the rest alone. Capitalize<"name"> is "Name", and Capitalize<"nAME"> is "NAME".
Its main job is generating camelCase names from words: getName, onClick, setEmail. Because it works on unions and template literal types, one definition can produce a whole family of method names from a list of property names.
type Field = "name" | "email"; type Getter = `get${Capitalize<Field>}`; // "getName" | "getEmail"
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 Capitalize<S extends string> = intrinsic;
| Name | Description |
|---|---|
S |
A string type. Literal types and unions give exact results; string yields the special Capitalize<string> type. |
Returns: S with its first character mapped to upper case.
Edge cases:
Capitalize<"">is"".- A union distributes:
Capitalize<"a" | "b">is"A" | "B". - The underscore in
key_downis not treated as a word boundary, soCapitalizegivesKey_down, notKeyDown.
Usage notes
- To get camelCase from snake_case you need a recursive template literal type that splits on
_and appliesCapitalizeto each part;Capitalizealone does not do it. - In a mapped type, intersect the key with
string(keyof T & string) before putting it in a template, since keys can also benumberorsymbol. - The runtime counterpart is
s[0].toUpperCase() + s.slice(1). The type does not run any code, so keep the two in sync (or add a test withEqual-style type assertions). - It does not lower-case the rest of the string; combine with Lowercase if you want "Title" style from "TITLE".
- Pairs naturally with Uncapitalize, which undoes it.
Related
- Uncapitalize
, Uppercase, Lowercase - Tutorial: Template literal types, Mapped types