Using Guard Conditions To Short-Circuit Object-Spread Operations In TypeScript 3.2.4

After my post yesterday on applying the Object-Spread operator to Null and Undefined values in TypeScript, Duncan Bay showed me another cool feature of the Object-Spread operator: you can use guard conditions to short-circuit spread operations. Off the top of my head, I don't have a great use-case for this; but, I thought it was an idea worth sharing.

To see this in action, I'm going to create a new object into which I randomly spread two other objects:

interface StringMap { [ key: string ]: string; } var target: StringMap = { a: "1" }; var value1: StringMap = { b: "2" }; var value2: StringMap = { c: "3" }; var clone: StringMap = { ...target, // This is a silly example; but, it's demonstrating that the Object-Spread operator // can use Boolean guard-conditions in order to short-circuit the individual spread // actions: we are randomly executing the spread of the two other values. ...( ( Math.random() < .5 ) && value1 ), ...( ( Math.random() < .5 ) && value2 ) }; console.log( "Clone:", clone );

As you can see, I'm using the following generalized concept:

...( truthy && spreadable )

When the "truthy" value is True, the expression returns "spreadable", which is then spread into the new structure. However, when the "truthy" is False, the expression returns the "falsey" value, which TypeScript quietly ignores as a non-spreadable value, which is essentially what we were seeing the last post (that Null and Undefined values were quietly ignored).

Now, if we run the above code, we get the following console output:

Pretty cool stuff! As you can see, every time we run the ts-node file, we get a randomly-spread result. If these conditions had meaningful variable names, instead of Math.random() calls, I think it would lead to rather elegant, very readable logic.

Tweet This Deep thoughts by @BenNadel - Using Guard Conditions To Short-Circuit Object-Spread Operations In TypeScript 3.2.4 Woot woot — you rock the party that rocks the body!







