Category: TypeScript

Use Static Factory Methods Instead of Constructors in TypeScript

The traditional way for a class in TypeScript to allow a user of the class to obtain an instance of it is to provide a public constructor. There is another useful technique that should be a part of every programmer’s toolkit.

Good Toolkit

A class can provide a public static factory method. Now don’t confuse this with the stuffy Factory Method pattern from that Design Patterns books. It’s not the same at all and has no direct equivalent in that book or other design pattern books. Also, using a static factory method instead of a public constructor has both advantages and disadvantages that you need to consider.

Read more…

TypeScript try/catch/finally and Custom Errors

Several years ago, the entire booking and check-in system for a major airline in the United States ceased to function for more than an hour during the morning rush on a weekday. This resulted in flight delays for the entire day all across the country. In the end, the cause was found to be an unhanded error that resulted in a flight lookup service to become completely unresponsive.

Handling errors in TypeScript and JavaScript is one of the fundamental things a developer should be experienced in. It’s as important as the rest of the code, and should never be overlooked or underestimated. This is a guide to help newer developers understand how to handle errors, throwing errors, and using try/catch/finally according to industry standards, and also how not to handle them.
Read more…

Using Short Imports in TypeScript

When importing modules (e.g. classes, interfaces, etc) in TypeScript, the most common method is to allow the IDE to create a relative import statement. Here is an example:

However, there is an easy way to completely avoid these long import statements. All it requires is some simple and minor modifications to your tsconfig.json file.
Read more…

Guide to Extract Method Refactoring in TypeScript

The purpose of the extract method refactoring is to turn a section of code into a new method. The method should be given a name that accurately describes the purpose of the extracted section of code. Extracting methods allows the code to be self documenting and also allows the code to be reused elsewhere thereby reducing duplication.

Read more…