Intrinsic String Manipulation Types
Intrinsic String Manipulation Types — the core idea
Uppercase, Lowercase, Capitalize, and Uncapitalize are built-in type operators on string literal types. They transform the set of strings permitted by TypeScript; they do not uppercase a JavaScript value for you.
What you’ll learn
- Explain intrinsic string manipulation types with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: Uppercase<Command> is "START" | "STOP". The uppercase value is assigned explicitly. At runtime toLowerCase() produces start; the assertion asks the checker to treat it as Command.
Keep the boundary clear: Never rely on an assertion such as as Command to validate arbitrary user input; validate membership before trusting it.
See the idea as a flow
Run the complete TypeScript example
Save the code as intrinsic-string-manipulation-types.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
type Command = "start" | "stop";
type Label = Uppercase<Command>;
const current: Label = "START";
const verb: Command = current.toLowerCase() as Command;
console.log(current);
console.log(verb);Verified output
START
startBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable intrinsic-string-manipulation-types.ts; run: node intrinsic-string-manipulation-types.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
Uppercase<Command> is "START" | "STOP". The uppercase value is assigned explicitly. At runtime toLowerCase() produces start; the assertion asks the checker to treat it as Command.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Never rely on an assertion such as as Command to validate arbitrary user input; validate membership before trusting it.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Declare Lowercase<"YES" | "NO"> and compare it with the runtime result of toLowerCase().
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
Uppercase, Lowercase, Capitalize, and Uncapitalize are built-in type operators on string literal types.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.