|
|
|
|
|
by aastronaut
1316 days ago
|
|
Thanks for the example! I guess we consider switch/case in different situations then. I usually make use of switches in simple mappings and switch/case seems more readable and idiomatic to me there: type CountryCode =
| "CH"
| "US";
function nameFromCountryCode(countryCode: CountryCode): string {
switch (countryCode) {
case "CH": return "Switzerland";
case "US": return "United States of America";
default: // exhaustiveness checking
((val: never): never => {
throw new Error(`Cannot resolve name for countryCode: "${val}"`);
})(countryCode);
}
}
...instead of... type CountryCode =
| "CH"
| "US";
function nameFromCountryCode(countryCode: CountryCode): string {
return ({
'CH': (() => 'Switzerland'),
'US': (() => 'United States of America'),
}[countryCode] || (() => {
throw new Error(`Cannot resolve name for countryCode: "${countryCode}"`);
}))();
}
|
|
Here's how you'd actually do it:
Your second example is way more complicated than your first, but this one is even easier to read (at least for me), and still provides all the same functionality and type safety (including exhaustiveness checking).