Git Product home page Git Product logo

typescriptexperiments's Introduction

TypeScript Experiments

This repository contains various experiments with TypeScript.

/json-deserialization

If you have ever worked with JSON in an Angular application, you know that you cannot trust the deserialized results. JavaScript doesn't have Reflection, JSON doesn't have a data type for a Date and so... JSON.parse doesn't know that you want the incoming string value "2018-07-15T05:35:03.000Z" converted into a Date.

Say you have defined an interface Order as:

export interface Order {
    orderId?: number;
    orderNumber?: string;
    pickupDateTime?: Date
}

You call your Angular HttpClient with the generic HttpClient#get<T> overload:

this.httpClient
    .get<Order>(url, ...)
    .pipe(
        map((response: Order) => {
            // Work with the Response ...
        })
    );

Your Webservice responds with a totally valid JSON Order as:

{ 
    "orderId": 1,
    "orderNumber": "8472-423-14",
    "pickupDateTime":"2018-07-15T05:35:03.000Z"
}

And with a simple test, we can see, that the returned pickupDateTime is actually a string and not a Date:

describe('JSON.parse', () => {

    it('Should not parse string as Date', () => {
        
        // prepare
        const json = `
        { 
            "orderId": 1,
            "orderNumber": "8472-423-14",
            "pickupDateTime":"2018-07-15T05:35:03.000Z"
        }`;

        // act
        const verifyResult = JSON.parse(json) as Order;

        // verify
        const isTypeOfString = typeof verifyResult.pickupDateTime === "string";
        const isInstanceOfDate = verifyResult.pickupDateTime instanceof Date;
        
        deepStrictEqual(isTypeOfString, true);
        deepStrictEqual(isInstanceOfDate, false);
    }); 
    
});

In this example we will take a look at providing a set of decorators (@JsonProperty, @JsonType, ...) to decorate classes and deserialize the JSON into the correct types. It will look like this:

export class Order {

    @JsonProperty("orderId")
    orderId?: number;

    @JsonProperty("orderNumber")
    orderNumber?: string;

    @JsonProperty("pickupDateTime")
    @JsonType(Date)
    pickupDateTime?: Date;
}

And with a simple test, we will see the correct types on our deserialized object:

describe('deserialize', () => {

    it('Decorated Order should parse Date', () => {
        // prepare        
        const json = `
        { 
            "orderId": 1,
            "orderNumber": "8472-423-14",
            "pickupDateTime":"2018-07-15T05:35:03.000Z"
        }`;

        // act
        const verifyResult: Order = deserialize<Order>(json, Order);

        // verify
        const isTypeOfObject = typeof verifyResult.pickupDateTime === "object";
        const isInstanceOfDate = verifyResult.pickupDateTime instanceof Date;
        
        deepStrictEqual(isTypeOfObject, true);
        deepStrictEqual(isInstanceOfDate, true);
    }); 
});

That enables us a bit more type-safety, when deserializing incoming JSON data.

typescriptexperiments's People

Contributors

bytefish avatar

Watchers

 avatar  avatar

Forkers

straiforos

typescriptexperiments's Issues

Number conversion and boolean

I get a response from Wordpress and unfortunately all Types are string. I need to convert them manually :-/

I'm thinking to use your approach. Is there a way to

  1. Convert a string into a number with the annotation?
  2. Convert a 0/1 value into a boolean?
  3. More or less the follow up of 1, but nevertheless: is there a way to grant that a given number is only 0,1,2 or 3? I can grant it by the Type definition. But can I grant it for the conversion? (either serialized deserialized)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.