ilbrando
ilbrando

Reputation: 75

Typesafe solution for using map and spread operator

Does anybody have a solution to this problem? I have an interface, say IFoo, and an array of data IFoo[]. I want to map these data and change a single property. Something like this

const mapper = (foos: IFoo[]): IFoo[] => {
  return foos.map((f) => {
    return {
      ...f,
      prop4: 42
    };
  });
};

The problem is that "prop4" does not exists in IFoo, but the compiler is happy, because I have used the spread operator "...f" and therefor all required props are set. But I meant to change "prop3" and doesn't see and doesn't get a compiler error.

Explict setting all properties is not a good solution, because it's tedious and if a new prop which can be undefined is added to IFoo one must remember to update this function.

You can see the complete example at codesandbox.io

Upvotes: 2

Views: 454

Answers (1)

Terry
Terry

Reputation: 66188

A solution would be perhaps explicitly stating the type of the merged object, so that it must be IFoo: then, TypeScript will know that the object can only contain properties listed in the IFoo interface, and warn you if that's not the case:

const mapper = (foos: IFoo[]): IFoo[] => {
  return foos.map((f) => {
    const foo: IFoo = {
      ...f,
      prop4: 42 // Error: 'prop4' does not exist in type 'IFoo'
    };

    return foo;
  });
};

See proof-of-concept on TypeScript playground.

Upvotes: 1

Related Questions