Cast JavaScipt object to TypeScript classes

TypeScript could give you a false hope that I’ve got a strong-typed code and everything will work as expected with JavaScript. In reality, TypeScript doesn’t do anything after sources are compiled to JavaScript. It means, in runtime, you’ll face good-known JavaScript with it dynamic typing.

The lack of any runtime type checking is a big minus for TypeScript. You’ll lose all your type at the same moment when browser executes code.

I’d got a pretty simple code in my Vue component:

data() {
        return {
            clouds: Array<Cloud>(),
        };
    }

And I use Axios to work with AJAX. I know that it’s a good time to use Fetch API but it’s a different story. My code looks like:

axios.get('/api/clouds/')
            .then((response) => {
                this.clouds = response.data;
            });

And here is Cloud class definition:

export class Cloud {
    public created_at: Date;
    public description: string;
    public name: string;
    public nodes: object;
    public updated_at?: Date;
    public id: string;
  }
}

I skipped some code to make it cleaner and fit it in the blog.

If you are experienced with TypeScript, probably you understand already what goes wrong. When I do this.clouds = response.data;, a browser will execute compiled to JavaScript code which doesn’t know anything about Cloud type. It means, that instead of an array of Cloud, I’ll get an array of simple JavaScript objects with primitive types. It works good enough until I use some specific Date methods and properties of my Cloud.created_at or Cloud.updated_at properties. Since TypeScript doesn’t do any type casting itself, cloud.created_at will be a string, not a Date object.

To fix it, I need manually convert JavaScript object to my TypeScript class. I added a static method to Cloud type to covert JavaScript to TypeScript objects:

static fromObject(obj: CloudObject): Cloud {
      let cloud = Object.create(Cloud.prototype);
      return Object.assign(cloud, json, {
        created_at: new Date(json.created_at),
      });
  }

All ‘magic’ is done by Object.assign function.

I introduced CloudObject interface just to verify types during the compile time and have my linter happy:

export interface CloudObject {
    created_at: Date;
    description: string;
    name: string;
    nodes: object;
    updated_at?: Date;
    id: string;
}

Tags

.net .net-framework .net-framework-3.5 agile ajax ajax-control-toolkit ampq ansible apache asp.net asp.net-mvc automation axum babel bash benchmark blog blog-engine bootstrap buildout c# cache centos chrome ci cinder ckan cli cloud code-review codeplex community config debugger deface dependencies development-environment devices devstack devtime disks django dlr dns docker dockerimage dos easy_install elmah encoding environment-variables error event events everything-as-a-code exception exceptions fabrik firefox flask foreach forms fstab gae gcc gerrit git github go google google-app-engine grep hack hacked hardware headless horizon hound html hugo iaas ienumerable iis internet iptables iron-python ironic iscsi java-script javascript jenkins jquery js jsx k8s kharkivpy kiss kombu kubernetes kvm kyiv lettuce libvirt linux lio loci logging loopback losetup lvm mac-os macos mercurial microsoft microsoft-sync-framework mobile mono ms-office msbuild networking news nginx npm npx offtopic oop open-source open-xml opensource openstack openvswitch os packages paraller-development patterns-practices performance php pika pip plugins pnp podcast popup postgresql profiler project protocols proxy pycamp pycharm pycon pykyiv pylint pypi python python-3 qcow quantum qumy rabbitmq rar react reactjs refactoring rfc rhel search-engine security selenium server shell silverlight socket software-engineering source-control sourcegear-vault sources sql sql-server sql-server-express sqlalchemy ssh static-site sublimetext svg tests tgt tipfy todo tornado typescript uapycon ui uneta unit-tests upgrades usability vim virtualenv visual-studio vitrage vm vue.js vuejs web-development web-server web-service web_root webpack webroot windows windows-live word-press x32 x64 xcode xml xss xvfb интернет-магазин книги

Recent posts

Go 1.18: new features

Всё будет Kubernetes

2022 Relaunch

Everyday Blogging

I don't want this CI


Archives

2022 (3)
2019 (73)
2018 (2)
2017 (3)
2016 (2)
2015 (3)
2014 (5)
2013 (17)
2012 (22)
2011 (36)
2010 (25)
2009 (35)
2008 (32)
2007 (2)