Category: Software Engineering

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.

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…

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:

import { ClassB } from '../../../../other/domain/ClassB';

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…