0

In other words; how can I convert

// an array of length >= 3
let myArray = returnOfSomeParametricFunction(); // assuming repeating rhs removes dryness

let myObj = { staticKeyName: myArray[1], anotherStaticKeyName: myArray[2] };

to a single liner. Perhaps something like:

let myObj = returnOfSomeParametricFunction().reduce(arr=> { staticKeyName: arr[1], anotherStaticKeyName: arr[2] };
Nae
  • 14,209
  • 7
  • 52
  • 79

1 Answers1

1

In this case, if I needed to do it in one line and not introduce a new variable in the same scope as myObj, and I didn't care about readability, I'd use an arrow function like this:

let myObj = (a => ({ staticKeyName: a[1], anotherStaticKeyName: a[2] }))(
  returnOfSomeParametricFunction());

You can verify that myObj has the properties of the right types. For example, given

declare function returnOfSomeParametricFunction(): [Date, number, string];

Then myObj would have type:

/*
let myObj: {
    staticKeyName: number;
    anotherStaticKeyName: string;
}
*/

Okay, hope that helps; good luck!

Playground link to code

jcalz
  • 264,269
  • 27
  • 359
  • 360