Home > other >  List to object with default values in Typescript
List to object with default values in Typescript

Time:12-18

The following function (without type declaration) behaves as expected in Javascript, but Typescript is raising the error A spread argument must either have a tuple type or be passed to a rest parameter for ...keysArray.

const arrayToMap = (keysArray: string[], defaultValue: any) => {
  const object = Object.assign(...keysArray.map((k) => ({ [k]: defaultValue })));
  return object;
};

How can this be solved? I already tried to put the spread operator in the function arguments without luck.

In Javascript:

const arrayToMap = (keysArray, defaultValue) => {
  const object = Object.assign(...keysArray.map((k) => ({ [k]: defaultValue })));
  return object;
};

console.log(arrayToMap(['a', 'b', 'c'], false))

CodePudding user response:

The issue is that the overload that accepts an array has the signature assign(target: object, ...sources: any[]): any. You can't spread any[] to [object,...any[]] because [object,...any[]] requires at least one element and any[] could have 0 elements.

This could be one solution:

const arrayToMap = (keysArray: string[], defaultValue: any) => {
  const object = Object.assign({}, ...keysArray.map((k) => ({ [k]: defaultValue })));
  return object;
};

Playground Link

  • Related