Within a nest.js service: I have a service method that takes an error code and outputs a message which is later on displayed to the user. The following method is a shortened version of it:
getGenericErrorMessage(input: string): string {
const errorMessages = {
unknownError: 'An unknown error occurred. ',
noResponse: 'The Application did not send a response. ',
};
return errorMessages[input] || errorMessages['unknownError'];
}
Is there a way to get intellisense for valid function parameters that are defined as keys in errorMessages
? Or is there any way I can restructure my code to archive this?
CodePudding user response:
You can move errorMessages
out then use keyof
like this:
const errorMessages = {
unknownError: 'An unknown error occurred. ',
noResponse: 'The Application did not send a response. ',
};
function getGenericErrorMessage(input: keyof typeof errorMessages): string {
return errorMessages[input]; // <--- // `input` must be `unknownError` or `noResponse`, so you can remove the fallback
}
If you want to discuss further, leave a comment below