0

I have spread-and-copy code where I am extracting a type from a super set. With the attribute list growing up, is there a more elegant way of doing this?

 const { name, handler, targetGrid, type } = event; //eg: event here is of type any
 let e: Event = {  name, handler, targetGrid, type } as Event;

Complete code: StackBlitz

The closest i could see is a solution here SO. But that would still merge my 2 lines to a single line, and eventually when the params grows big, lint would ask me to break the lines....

Am looking for a solution where I wouldn't have to repeat the attribute names twice.

Raghav
  • 2,402
  • 4
  • 27
  • 49
  • 1
    and https://stackoverflow.com/questions/25553910/one-liner-to-take-some-properties-from-object-in-es-6 - in short, not really – CertainPerformance May 11 '20 at 08:27
  • https://stackoverflow.com/a/57508781/709333 This does... Am trying it out with type guards – Raghav May 11 '20 at 08:36
  • To think about a different approach. What could be the need of extracting properties from an object? For `TypeScript` it doesn't matter if an object has more properties than listed in the interface. So you can just do: `event as Event` and you're done.. – Poul Kruijt May 11 '20 at 08:40
  • @PoulKruijt you don't even need the assertion `let e: Event = event;` will run successfully, assuming `event` has the properties to satisfy the `Event` interface. Again, any extra ones would be ignored and the compiler would stop you from doing `e.otherProperty`. – VLAZ May 11 '20 at 08:47

1 Answers1

0

Kind of a messy approach, but it does what you want:

let e: Event = ["name", "handler", "targetGrid", "type"].reduce((a, c) => (a[c] = event[c], a), {});
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67