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.
Code
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
trueUsing 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.