I need to create an interface that is either a string or an object with one of three keys.
Basically I have a function that depending on the error returns something:
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;
}
};
Here are the 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];
}
But the way I designed ServerAlerts
here does not work for me, since ServerAlerts can also be a string
and if it has one of its keys, it only has one.
How would you design such a type or interface?
EDIT: I tried making the keys optional by giving them a question mark, but then my linter complains in the respective key's error return statement in determineError
.