You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免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.

1. Better Validation for Union Types (Your Nested Code 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 is null or undefined
  • ?? returns the right-hand value only if the left is null or undefined (unlike ||, it doesn’t trigger on falsy values like 0 or 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.

2. Using 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:56:17