-
Notifications
You must be signed in to change notification settings - Fork 0
Narrowing Unions
Jorge Castro edited this page Nov 10, 2025
·
1 revision
In this example, property 'toUpperCase' does not exist on type 'number'
function printId(id: number | string) {
console.log(id.toUpperCase());
}The solution is to narrow the union to deduce a more specific type for a value based on the structure of the code.
function printId(id: number | string) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id);
}
}- Sync-Obsidian-with-GitHub-on-iOS
- Obsidian-community-plugins
- Optimizing-Novel-Word-Count-Plugin-for-Git-Users
- What is TypeScript, and why you should use it
- Quick setup
- Inference and type annotations
- Fundamental Types
- Object Types
- Union Types
- Type Aliases and Interfaces
- Type Assertions
- Literal Types
- null and undefined
- Narrowing
- Creating Types from Types
- Common Built‐in and Utility Types
- tsc CLI ‐ (The Compiler)
- Avoid using Object or {}
- Ignoring TypeScript errors
- TypeScript resources