I am tasked with creating an interface that can either be a string or an object with one of three specific keys.
The function I have takes care of different errors and returns the appropriate message:
export const determineError = (error: ServerAlerts): AlertError => {
if (typeof error !== "string") {
if (error.hasOwnProperty("non_field_errors")) {
return error.non_field_errors[0];
} else if (error.hasOwnProperty("detail")) {
return error.detail;
} else if (error.hasOwnProperty("email")) {
return error.email[0];
} else {
return UNKNOWN_ERROR;
}
} else {
return error;
}
};
These are the defined types:
export type AlertError =
| "Unable to log in with provided credentials."
| "E-mail is not verified."
| "Password reset e-mail has been sent."
| "Verification e-mail sent."
| "A user is already registered with this e-mail address."
| "Facebook Log In is cancelled."
| string;
export interface ServerAlerts {
non_field_errors: [string];
detail: string;
email: [string];
}
However, my current design for ServerAlerts
doesn't fully meet my needs. It should also accommodate cases where ServerAlerts could be just a plain string, and when it has one key, it only contains one value.
How would you suggest redesigning the type or interface to handle these scenarios?
EDIT: I attempted to make the keys optional by adding question marks, but then my linter raises concerns in the error return statements of determineError
.