Monday, March 12, 2018

mixing arrays and objects with the spread operator in TypeScript

let x = [13, 42, 69, 86];
let y = {
   foo: 13,
   bar: 42,
   baz: 69,
   qux: 86,
};
let z = {
   ...x,
   ...y
};
console.log(z);

 
 

...creates an object like this:

{
   0: 13,
   1: 42,
   2: 69,
   3: 86,
   bar: 42,
   baz: 69,
   foo: 13,
   qux: 86
}

 
 

While...

let x = [13, 42, 69, 86];
let y = {
   foo: 13,
   bar: 42,
   baz: 69,
   qux: 86,
};
let z = [
   ...x,
   ...y
];
console.log(z);

 
 

...has a squiggly red line for "I can't compile" at the TypeScript Playground, but also returns an array like this...

[13, 42, 69, 86, {foo: 13, bar: 42, baz: 69, qux: 86}]

No comments:

Post a Comment