如何抛出含复杂对象的错误?解决SubmissionError/stopSubmit的TS类型问题
Great question! The constraint that _error must be a string in TypeScript definitions is indeed a common pain point when you need to pass multiple errors or complex error objects. Here are the standard, TypeScript-friendly solutions to handle this:
1. Use Field-Specific Errors Instead of Global _error
First, if your errors are tied to individual form fields, the cleanest approach is to map errors directly to their respective fields instead of relying on the global _error. This aligns with the intended design of form libraries like redux-form:
throw new SubmissionError({ email: ['Invalid format', 'Already registered'], password: { message: 'Password too weak', requirements: ['Min 8 characters', 'Include at least one number'] }, // No need for _error here if errors are field-specific });
This way, each field can hold arrays, objects, or any custom data type. You can even extend the field error type in TypeScript to enforce your desired structure for full type safety.
2. Extend TypeScript Definitions for Global _error
If you truly need a global error that's a complex object or array, you can safely augment the library's TypeScript types to allow _error to accept more than just strings. This is the standard, type-safe way to override or extend existing type definitions:
Create a .d.ts file (e.g., form-types.d.ts) in your project with the following content:
declare module 'redux-form' { // Update SubmissionError options to support complex _error interface SubmissionErrorOptions { _error?: string | string[] | Record<string, unknown> | Array<Record<string, unknown>>; } // Also update the stopSubmit action payload type interface StopSubmitActionPayload { _error?: string | string[] | Record<string, unknown> | Array<Record<string, unknown>>; } }
This tells TypeScript that _error can be a string, array, or object, eliminating the type error while keeping your code fully type-safe.
3. Serialize Complex Errors (Alternative, Less Preferred)
If you prefer not to extend types, you can serialize your complex error into a string (like JSON) and parse it back in your component. While functional, this adds extra overhead and isn't as clean as the above methods:
// In your submit handler throw new SubmissionError({ _error: JSON.stringify({ generalErrors: ['Server timeout', 'Invalid session'], errorCode: 500 }) }); // In your component const globalError = formError._error ? JSON.parse(formError._error) : null;
Remember, the first approach (field-specific errors) is always recommended if your errors are associated with individual fields. The type extension method is the standard solution for global complex errors when you need them.
内容的提问来源于stack exchange,提问作者Hristo Kolev

