Sobes.tech
Junior — Senior

Improving the typing of a function that creates an array of values from an object

livecode

Task condition

It is required to improve the type definition of a function that collects an array of values from a given object based on a set of keys. The function should work correctly even if some of the requested keys are missing in the object, and should not cause compilation errors in TypeScript.

const arrayFromKeys = (obj: Record<string, any>, keys: string[]) => { 
  const out = [];
  for (const key of keys) {
    out.push(obj[key]);
  }
  return out;
}
const obj = {
  a: 1, 
  b: 'B',
  'c d': null,
}

// Error
arrayFromKeys(obj, ['z']);