Home > database >  Using an enum and a payload map to get an implicit second argument of undefined
Using an enum and a payload map to get an implicit second argument of undefined

Time:06-11

I'm currently writing a function that takes two arguments. The first being the key of an enum, and the second depends on the first argument.

Some of the keys don't require a second argument, so when I assign undefined in the payload map, the function explicity requires to pass in undefined.

Is there a way I can pass in the first key, and not pass in a second argument, while fulfilling the type requirements?

Code:

export enum MyKey {
  BleepBloop = 'BleepBloop',
  BeepBoop = 'BeepBoop',
  BingBong = 'BingBong',
}

export type SubstitutionsMap = {
  [MyKey.BleepBloop]: [string, string];
  [MyKey.BeepBoop]: [string, string];
  [MyKey.BingBong]: undefined;
};

export const getFoo = <K extends MyKey>(key: K, substitutions: SubstitutionsMap[K]): string => {
    // Handle private logic
    return ''
};

getFoo(MyKey.BingBong) // <--- Error is here

Error:

(enum member) MyKey.BingBong = "BingBong"
Expected 2 arguments, but got 1.ts(2554)
index.ts(13, 49): An argument for 'substitutions' was not provided.

This error is gone when I explicitly pass in undefined, but I would like to not have to pass in a second argument if it's just undefined.

This fixes my error:

getFoo(MyKey.BingBong, undefined)

CodePudding user response:

You could create function overloads for getFoo that matches your required types.

Something like below:

function getFoo(key: MyKey.BingBong): string;
function getFoo<K extends MyKey.BeepBoop | MyKey.BleepBloop>(
  key: K,
  substitutions: SubstitutionsMap[K]
): string;
function getFoo(key: MyKey, substitutions?: SubstitutionsMap): string {
  if (key === MyKey.BingBong) {
    // code in which I don't need substitutions
  }

  if (substitutions) {
    // code in which I do need to access substitutions
  }

  return '';
}

getFoo(MyKey.BleepBloop);                 //error!
getFoo(MyKey.BleepBloop, ['asd', 'qwe']); //fine
getFoo(MyKey.BeepBoop);                   //error!
getFoo(MyKey.BeepBoop, ['asd', 'qwe']);   //fine
getFoo(MyKey.BingBong);                   //fine
getFoo(MyKey.BingBong, ['asd', 'qwe']);   //error!

This will make it so that when the first argument is MyKey.BingBong, it will not let you pass a second argument, but if it is another member of MyKey, it will require you to pass a second argument.

  • Related