In JavaScript and/or TypeScript, what is the common approach to solving the following problem?
Assume we have a class whose constructor depends on some operation. If that operation fails, the instance should not be created.
Example:
class Item {
constructor(itemId) {
// Try to get the data for the passed-in item id
const itemData = itemDataMap.get(itemId);
// If the item data was found
if (itemData) {
// Great, continue to init the instance as normal...
}
else {
// Problem: We can't init the instance without the item data.
// Hence we don't want to return an instance.
// What should we do here?
}
}
}
Solutions I can think of include trying to return an empty object, or throwing an error. But is there a common/preferred approach?