Nice article. I'll just add that unless MONTH_TO_TRANSLATION_KEY is a dynamic object that could be changed at some point, you could simplify this by using the keyof typeof keywords to pull the object keys directly from the object, so you don't need to explicitly define the keys:
Given that object keys can only be strings or symbols (numbers are coerced to strings) Maps are useful as well:
constMONTH_KEY_ENTRIES=[['January','JANUARY_TRANSLATION_KEY'],['February','FEBRUARY_TRANSLATION_KEY'],['March','MARCH_TRANSLATION_KEY'],['April','APRIL_TRANSLATION_KEY'],['May','MAY_TRANSLATION_KEY'],['June','JUNE_TRANSLATION_KEY'],['July','JULY_TRANSLATION_KEY'],['August','AUGUST_TRANSLATION_KEY'],['September','SEPTEMBER_TRANSLATION_KEY'],['October','OCTOBER_TRANSLATION_KEY'],['November','NOVEMBER_TRANSLATION_KEY'],['December','DECEMBER_TRANSLATION_KEY'],]asconst;typeEntryKey<T>=Textendsreadonlyany[]?T[0]extendsundefined?never:T[0]:never;typeEntryValue<T>=Textendsreadonlyany[]?T[1]extendsundefined?never:T[1]:never;typeMonthKeyEntries=typeofMONTH_KEY_ENTRIES[number];typeMonth=EntryKey<MonthKeyEntries>;typeTranslationKey=EntryValue<MonthKeyEntries>;constTranslationKeyMap=newMap<Month,TranslationKey>(MONTH_KEY_ENTRIES);functiontoTranslationKey(month:Month):TranslationKey{constXKey=TranslationKeyMap.get(month);if(typeofXKey==='undefined')thrownewError(`Missing month ${month} in TranslationKeyMap`);returnXKey;}
Nice article. I'll just add that unless
MONTH_TO_TRANSLATION_KEYis a dynamic object that could be changed at some point, you could simplify this by using thekeyof typeofkeywords to pull the object keys directly from the object, so you don't need to explicitly define the keys:Oh thanks a lot for the tip!
It makes sense to add a
constassertion:Given that object keys can only be strings or symbols (numbers are coerced to strings) Maps are useful as well: