what is typescript for an array of certain values where each value may appear at least once?

You can use Set type capability to extract only unique members of passed argument:

function getUserInfo(desiredProperties: ('name' | 'age' | 'salary')[]) {
  const uniqueMembers = new Set(desiredProperties); // this extract only unique members of array
  const userInfo: Record<string, unknown> = {};
  for (const propertyName of uniqueMembers) { // and here you iterate only through unique members
    userInfo[propertyName] = fetchEffortfullyFromDatabase(...);
  }
  return userInfo;
}

let userInfo = getUserInfo(['name', 'salary']);

userInfo = getUserInfo(['name', 'name', 'name']);

Of course, such a solution is not perfect, because it assumes runtime unnecessary computations.

If you don’t want to have unnecessary computations, you can set the type of desiredProperties as Set<'name' | 'age' | 'salary'>. And then call to getUserInfo like this:

const userInfo = getUserInfo(new Set(['name', 'salary']));

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top