Capitalize Mutates String Types In Place

The intrinsic Capitalize type transforms literal unions inside the type system, so mapped keys like onHomeClick are derived and checked, never hand-written.

TypescriptConfig Management

Code

typescriptsnippet
21 lines
type Route = "home" | "settings" | "billing";

// Intrinsic string manipulation types 在类型层变换字面量,且分布式作用于联合
type Label = Capitalize<Route>;              // "Home" | "Settings" | "Billing"
type Prefix = `on${Capitalize<Route>}Click`; // "onHomeClick" | ...

type Handlers = { [K in Prefix]: () => void };

const handlers: Handlers = {
  onHomeClick: () => console.log("home clicked"),
  onSettingsClick: () => console.log("settings clicked"),
  onBillingClick: () => console.log("billing clicked"),
};

// 拼错事件名编译报错:Handlers 上不存在 onhomeClick
handlers.onSettingsClick();

type ExpectEqual<T, U> =
  (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : never;
const a: ExpectEqual<Label, "Home" | "Settings" | "Billing"> = true;
console.log(a);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

settings clicked
true

Using it

Running the file prints two lines: settings clicked (the only handler main calls) and true (the type-level equality check). The home and billing handlers are declared but never invoked.

Output is labeled for readability — expect lines prefixed with settings clicked and the bare true verdict.

Key statements worth quoting

(<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : never;
type Handlers = { [K in Prefix]: () => void };

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared.