All About Software Development

Menu

In light of what I posted yesterday about reducing the amount of TypeScript I write, I wanted to talk about another aspect of reducing the amount of TypeScript code. Once common task is to create TypeScript models for your Angular application that match what your server expects. You generate your TypeScript models for your .NET classes via another T4 template. You can use the approaches mentioned on StackOverflow. I used the T4 template from the article as a base. My only suggestion would be to put this template at the root of your solution, then use it as include in the template files that generate the code. This way you do not need to have multiple version of the template floating around your solution. I made a small enhancement to it, adding support for nullable types. The next issue I encountered was the code that typically resided under New function in Angular controllers. The code is similar to the following:

Although there is not much code to write in this case, the problem becomes much bigger when your .NET class contains dozens of properties. Would it not be nice if we could generate this code, using default values for each type? We want to use empty string for string properties, zeros for numbers, nulls for nullable properties, etc… I wanted to expand on model generation and create a T4 template that generates factories for my TypeScript models. I call them factories because they create instancees of my models. Here is what I wrote to solve this issue.

You can take this code and paste it into a new t4 file and place it in a solution folder. You notice that at the top I include all assemblies that I use in my solution to avoid including them in each tt file that is using this template. The main method is Factory<T>. This method takes a single type that I want to generate a factory for. This code creates new TypeScript class with a single create static method. This method runs through all the properties of the class. It figures out simple properties and creates defaults for them, based on property type. For complex properties this method recursively calls the same code, generating object literal for each complex type property. At the end I end up with the same code as I shown in the beginning of the article.

To use this template inside another tt file, I just need to make new file look like the following:.

The code above assumes that there is a file that contains IMyClass interface / model definition. I manually add a line that imports this type. You can play around and use conventions to remove this requirement. Once I run this tt file / template, the code looks something like the following.