Using `Object.assign()` - Type Assertions in TypeScript - Part 2

Last week I wrote about using `as type` in TypeScript to perform type assertions. The gist is that you convert a generic object, or JSON object into a custom object, like this:

view plain print about
1myJSON as MyCustomClass

Once you do that, IDEs can introspect the object for code hinting purposes, and the TypeScript compiler will show errors if you access non-existent properties or methods. The problem is that this is just a compile time syntax and does not perform runtime type conversions. The use of get/set properties in the underlying object will not throw compiler errors, but will also fail in the UI code.

Thankfully there is another way.

Object.assign()

Built right into modern versions is Object.assign(). What this can be used for is move all the properties from one object into another. Any existing properties will be overwritten. Any new properties will be added to the object.

Here is a quick sample modeled after the link above:

view plain print about
1const target = { a: 1, b: 2 };
2const source = { b: 4, c: 5 };
3Object.assign(target, source);
4console.log(target);
5console.log(source);

The target object has two properties: a and b. The source object has two properties: b and c. After object.assign() is executed, the target object will have three properties: a, b, and c. The original value of b--2--will be replaced with the source's value for b--4.

Run this in a browser:

Simple enough.

Using Object.assign() as Type Conversion

How do we use an Object.assign() to convert regular JSON to an instance of our custom class? You can find our custom class sample in last week's article.

view plain print about
1const testClassAssign = Object.assign(new TestClass(), {numbers : [1, 2, 3, 4]});
2console.log(testClassAssign.sum); // returns 10

The first argument to the Object.assign() is a brand new instance of the TestClass. This instance gives us access to all the properties and methods in the class, including the get/set properties. The second argument is our custom JSON, or other generic object. All the properties from the generic object will be copied over to the new TestClass instance, essentially creating our full object:

You see in Chrome Dev tools that the new resulting class has the full type listed. Look at the console and you'll see the proper output for the second line:

This is what we wanted, and is important if you want to access any sort of custom method inside your class, while also touching on properties.

You can get all the samples from these two blog articles from my Github account.

Related Blog Entries

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)

Comments are not allowed for this entry.