Home > Mobile >  Return object where each key is an element of enum array
Return object where each key is an element of enum array

Time:07-15

I am currently building a function that takes an array of enum members and returns an object where each array element is a key and the value is a string array, containing the possible options for the corresponding dropdown (in the example where I have enum Seasons this might for example return all the holidays in that season).

For now I am typing the result as Partial<Record<Seasons, string[]>> which works but is cumbersome since I already know which keys the return type is supposed to have: All the elements of the function argument.

Is there a more elegant solution for this problem where the keys are strictly typed? I suppose one would have to use generics but I don't have a clue how.

// dummy implementation
async function getGroupFromDb(group: Seasons): Promise<string[]> {
  return [];
}

enum Seasons {
  Spring = 1001,
  Summer = 1002,
  Fall = 1003,
  Winter = 1004,
}

export async function getGroupOptions(groups: Seasons[]): Promise<Partial<Record<Seasons, string[]>>>{
  const result: Partial<Record<Seasons, string[]>> = {};

  for(const group of groups){
    // find options in database
    result[group] = await getGroupFromDb(group);
  }

  return result;
}

Playground Link

CodePudding user response:

You probably want something like this:

export async function getGroupOptions<
  T extends Seasons[]
>(groups: T): Promise<Record<T[number], string[]>> {
  const result: Partial<Record<Seasons, string[]>> = {};

  for(const group of groups){
    // find options in database
    result[group] = await getGroupFromDb(group);
  }

  return result as Promise<Record<T[number], string[]>>;
}

We can store the elements passed as groups in the generic type T. The return type of the function would be a Record where the keys are T[number].

Playground

  • Related