Skip to main content
Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.

You Can Safely Apply Object-Spread To Null And Undefined Values in TypeScript 3.2.4

By Ben Nadel on

I just wanted to share a cool feature of TypeScript that I stumbled across the other day: TypeScript will silently ignore the attempt to spread Null or Undefined values into an Object literal. This means that you don't have to jump through hoops in order to avoid errors if you are dealing with values that may be optionally defined.

To see this in action, I put together a small ts-node demo that attempts to clone an object while also using the object-spread operator to mix-in both a Null and Undefined value:

interface StringMap {
	[ key: string ]: string;

var thing: StringMap = {
	hello: "world"

console.log( "Thing:", thing );
// We are going to try creating a clone of "thing" in which we also attempt to spread
// both a NULL and UNDEFINED value into the clone operation.
console.log( "Clone:", cloneAppend( thing, null, undefined ) );

// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //

function cloneAppend(
	target: StringMap,
	value1: StringMap | null | undefined,
	value2: StringMap | null | undefined
	) : StringMap {

	var clone: StringMap = {,

		// Notice that these values being spread into the clone can be NULL or UNDEFINED.
		// TypeScript has no issues with attempting to spread them without error.

	// NOTE: The rationale for this Object-spread behavior is that it maps to the default
	// behavior of the equivalent Object.assign() operation.
	// --
	// Read More:
	Object.assign( clone, value1, value2 );

	return( clone );


As you can see, the cloneAppend() method is taking both null and undefined as arguments and attempting to spread them into the returned clone. And, when we run this, we get the following console output:

Applying the object-spread operator to null and undefined values in TypeScript 3.

As you can see, no errors - the object-spread operator safely ignored the null and undefined argument, leaving us with a working clone of the target. I was just delighted to see that this worked as it reduces the amount of logic needed in the TypeScript code which should, in turn, make the code easier to read and maintain.

Reader Comments

Hi Ben, I cannot find this feature mentioned in the typescript changelog. Could you please show me where is mentioned?

Thanks! You've been very helpful to me since the days of AngularJS, keep the good work!