Skip to content
Tutorials Center
My learning

Topics

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.

TypeScript
type Field = "name" | "email";
type Getter = `get${Capitalize<Field>}`; // "getName" | "getEmail"

Try it

TypeScript Getters generated from an object type

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.

TypeScript Event handler names

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

TypeScript
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_down is not treated as a word boundary, so Capitalize gives Key_down, not KeyDown.

Usage notes

  • To get camelCase from snake_case you need a recursive template literal type that splits on _ and applies Capitalize to each part; Capitalize alone 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 be number or symbol.
  • 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 with Equal-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.