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

函数参数中的|符号代表什么含义?附TypeScript示例

What does the | symbol mean in a TypeScript function parameter?

Hey there! That vertical bar (|) in your function's parameter type is a union type—a key feature in TypeScript that lets you define a value that can be one of several different types.

In your example:

handleError(error: Error | HttpErrorResponse) { ... }

This tells TypeScript that the error argument passed to handleError can be either a standard JavaScript Error object, or an Angular HttpErrorResponse object.

Why is this useful?

Union types let you write flexible yet type-safe code. Instead of using any (which turns off TypeScript's type checking), you can explicitly list the valid types the parameter can accept. Inside the function, you can use type guards (like instanceof) to handle each type appropriately:

handleError(error: Error | HttpErrorResponse) {
  if (error instanceof HttpErrorResponse) {
    // Handle HTTP-specific errors (e.g., status codes, response bodies)
    console.error(`HTTP Error: ${error.status} - ${error.message}`);
  } else {
    // Handle generic runtime errors
    console.error(`Error: ${error.message}`);
  }
}

This way, TypeScript will enforce that you only access properties/methods that exist on both types (or narrow the type with a guard to access type-specific members).

内容的提问来源于stack exchange,提问作者Emenpy Nguyen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:11:03