Reputation: 26117
I have the following code and I would like to refactor it by using a dictionary or something like that, to reduce the code complexity. It is possible there can be any number of case statements.
switch (this.errorType) {
case ErrorType.NoApps:
this.title = 'No Apps Found';
this.subtitle = 'Contact applications team';
this.message = 'no apps message';
this.contact = 'John';
break;
case ErrorType.NoAccounts:
this.title = 'No Accounts Found';
this.subtitle = 'Contact Support Team';
this.message = 'no accounts message';
this.contact = 'Jake';
break;
case ErrorType.NoUsers:
this.title = 'No users Found';
this.subtitle = 'Contact customer service';
this.message = 'no accounts message';
this.contact = 'Wiley';
break;
}
Upvotes: 2
Views: 566
Reputation: 2564
I had once a quite similar problem. This is my modular and typesafe solution for it:
enum ErrorType {
NoApps,
NoAccounts,
NoUsers
}
type ErrorDetails = {
title: string
subtitle: string
message: string
contact: string
}
const errorTypes: { [key in ErrorType]: ErrorDetails } = {
[ErrorType.NoApps]: {
title: "No Apps Found",
subtitle: "Contact applications team",
message: "no apps message",
contact: "John"
},
[ErrorType.NoAccounts]: {
title: "No Accounts Found",
subtitle: "Contact Support Team",
message: "no accounts message",
contact: "Jake"
},
[ErrorType.NoUsers]: {
title: "No users Found",
subtitle: "Contact customer service",
message: "no accounts message",
contact: "Wiley"
}
}
[key in ErrorType]
makes it typesafe. If you add something to the enum it will throw an error till you implement the details for it.class Example {
errorType = ErrorType.NoAccounts
error: ErrorDetails | null = null
constructor() {
if (this.errorType)
this.error = errorTypes[this.errorType]
console.log(this.error)
}
}
new Example()
this.errorType
from an API (or it's a string or number) you can use this.errorType as ErrorType
Runnable snippet on codesandbox.
Upvotes: 4