函数参数中的|符号代表什么含义?附TypeScript示例
| 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

