如何避免TypeScript嵌套if语句?如何优雅处理联合类型校验?
Great question—those nested null/undefined checks can get really messy fast, especially as your code gets deeper. Let’s break down practical solutions for both of your questions, using your provided code as a concrete example.
That nested if chain you shared is a perfect example of how null checks can spiral into hard-to-read code. Here are three clean ways to fix it:
Option 1: Use Optional Chaining (?.) + Nullish Coalescing (??)
TypeScript (and modern JavaScript) has built-in operators to eliminate these nested checks in one go:
// Safely traverse the chain—stops and returns undefined if any step fails const medicineCategory = e?.toElement?.textContent; // Only update the DOM if we have a valid non-null/non-undefined value if (medicineCategory) { $('#selected-medicine-info').text(medicineCategory); }
Or even more concise, if you want a fallback value when no valid category exists:
$('#selected-medicine-info').text(e?.toElement?.textContent ?? 'No category selected');
?.stops evaluation immediately if any preceding value isnullorundefined??returns the right-hand value only if the left isnullorundefined(unlike||, it doesn’t trigger on falsy values like0or empty strings)
Option 2: Early Returns (Flat, Readable Code)
If you prefer explicit checks over operators, flatten the chain with early returns. This keeps your code linear instead of nested:
// Exit early if any required value is missing if (!e) return; const targetElement = e.toElement; if (!targetElement) return; const medicineCategory = targetElement.textContent; if (!medicineCategory) return; // Now we know all values are valid—no nesting needed! $('#selected-medicine-info').text(medicineCategory);
Option 3: Custom Type Guards (For Complex Types)
If you’re dealing with custom union types (not just null/undefined), you can write a type guard to validate the entire structure at once:
// Define a guard to check if an element has non-null text content function hasValidTextContent(element: Element | undefined): element is Element { return element !== undefined && element.textContent !== null; } if (e && hasValidTextContent(e.toElement)) { $('#selected-medicine-info').text(e.toElement.textContent); }
TypeScript will recognize that inside the if block, e.toElement.textContent is definitely a string, no extra checks needed.
let x: Type | undefined = variable to Avoid Nested Ifs The key here is to "lift" nested values into top-level variables with union types, then validate them once instead of nesting checks. Let’s use a generic example to show how this works:
Suppose you have this nested code:
if (user) { if (user.profile) { if (user.profile.bio) { displayBio(user.profile.bio); } } }
Step 1: Assign the nested value to a union-type variable
// user.profile.bio could be string | undefined (if any parent is null/undefined) const userBio: string | undefined = user?.profile?.bio;
Step 2: Validate once, no nesting needed
if (userBio) { displayBio(userBio); }
TypeScript automatically narrows the type of userBio from string | undefined to string inside the if block, so you don’t need any nested checks.
For more complex union types (e.g., string | number | null), you can use type narrowing with typeof or custom guards:
const value: string | number | null = getSomeValue(); if (typeof value === 'string') { // value is now typed as string handleString(value); } else if (typeof value === 'number') { // value is now typed as number handleNumber(value); } // No nested checks—each branch handles one specific type
内容的提问来源于stack exchange,提问作者Craig Jacobs

