0

My coworkwer, who left recently, wrote this and I'm trying to understand how to best catch errors if an invalid key is passed to the parent function. This child function uses that key to map the call of another function to return appropriate formatting for currencies.

Fairly new to JavaScript, so this is challenging for me. It doesn't seem like I can easily call the key for the mapping I made in the numTypeMap function?

I tried calling keys on the object or use toString to see if it would output the mapping options in some way. I'm probably misunderstanding something basic about JS.

export const getFormattedValue = (
  value: number | null | undefined,
  numType: string,
  options?: { round?: boolean; expanded?: boolean }
): string => {
  if (value === null || value === undefined) {
    return '';
  }
  const numTypeMap: { [t: string]: (n: number, round?: boolean, expanded?: boolean) => string } = {
    number: toReadableNumber,
    percent: toReadablePercentage,
    dollar: toReadableDollar,
    canadianDollar: toReadableCanadianDollar,
    pound: toReadablePound,
    euro: toReadableEuro,
  };
  return numTypeMap[numType](value, options?.round, options?.expanded) as string;
};
Slacker101
  • 23
  • 6
  • What specific issue are you having? You need to check if “numType” is one of the keys. – Dave Newton Dec 20 '22 at 22:03
  • the `numType` parameter should be of `keyof typeof numTypeMap` though this requires the type not be defined inline. Declaring the type before hand makes better use of TypeScript and will allow realtime error checking and autocomplete – pilchard Dec 20 '22 at 22:04
  • ie. [playground](https://tsplay.dev/N5OVMW) – pilchard Dec 20 '22 at 22:10
  • Thank you Dave Newton and @pilchard this makes it way clearer to understand. Though now I get thrown `"Argument of type 'string' is not assignable to parameter of type '"number" | "euro" | "dollar" | "canadianDollar" | "pound" | "percent"'."` so I am going to have to import numTypeMap into each place I call it and assign the type to that for the parameter, right? – Slacker101 Dec 20 '22 at 22:26
  • A more complete example might look like this: [tsplayground](https://tsplay.dev/NDDAlN). This gives you both the `Record` type as well as the the `keyof ` union of string keys. Based on this answer: [Get keys of a Typescript interface as array of strings](https://stackoverflow.com/questions/43909566/get-keys-of-a-typescript-interface-as-array-of-strings) – pilchard Dec 20 '22 at 22:41
  • `if(!(numType in numTypeMap)) { return ''; }` – Yogesh Kumar Gupta Dec 21 '22 at 04:33

0 Answers0