Casting date string from Http Json response using Decorator in Angular

One of the important benefits of using Typescript is its strongly typed, so it provides compiled time type checking and developers can work more efficiently in large and complex Apps. That is also why we will like to convert the Http Json response to a strongly typed object in Angular App.

A very simple and common example is to use typescript interface to “cast” the Json response into the defined data structure as below:

export interface IRepo {
name: string;
created_at: Date;
}
...
// Use interface IRepo to "Cast" the resposne
const path = 'https://api.github.com/repos/libgit2/libgit2sharp';
return this.http.get<IRepo>(path);

So in the component, we can simply use the property to bind to html.

{{repo.name}}

But if we try to format the “created_at” date property, we hit a problem

x.created_at.toLocaleDateString("en-US")Error: x.created_at.toLocaleDateString is not a function

The error is thrown because the “created_at” is a string, although it is declared as “Date” in the IRepo interface.

The root cause of the issue is the interface in type script is just for compiler, it is not in the generated java script, so this interface “cast” method is actually a type checking, or type assertion.

Type assertion allows you to set the type of a value and tell the compiler not to infer it. This is when you, as a programmer, might have a better understanding of the type of a variable than what TypeScript can infer on its own.

Since there is no date type in Json format, so the date is treated as string. If we want to get a real date type for “created_at”, we have to transform it explicitly.

Since the above use case is very common, we want to write a piece of code that can be used for all the Http response handling in our App.

Decorator is the right tool for this because it is written as a function, but can be added as meta data to a class declaration, method or property. In another word, it is “write once, use everywhere”.

The gist of the decorator is pretty straight-forward.

The stringToDate function will iterate through the object properties and converts the string property in ISO format to date.

The usage of the decorator is simply as below

Now, we can use the “created_at” as a real date type in the component.

x.created_at.toLocaleDateString("en-US")

The decorator can be applied to all the methods that returns Http Json response. Of course, it needs to be improved to handle more complex data structure, like a object with Array and nest object propertis, but you get the idea.

You can find this example in StackBlitz, Happy programming.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store