Book Image

TypeScript Design Patterns

By : Vilic Vane
Book Image

TypeScript Design Patterns

By: Vilic Vane

Overview of this book

In programming, there are several problems that occur frequently. To solve these problems, there are various repeatable solutions that are known as design patterns. Design patterns are a great way to improve the efficiency of your programs and improve your productivity. This book is a collection of the most important patterns you need to improve your applications’ performance and your productivity. The journey starts by explaining the current challenges when designing and developing an application and how you can solve these challenges by applying the correct design pattern and best practices. Each pattern is accompanied with rich examples that demonstrate the power of patterns for a range of tasks, from building an application to code testing. We’ll introduce low-level programming concepts to help you write TypeScript code, as well as work with software architecture, best practices, and design aspects.
Table of Contents (15 chapters)
TypeScript Design Patterns
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

Getting your hands on the workflow


After setting up your editor, we are ready to move to a workflow that you might use to practice throughout this book. It can also be used as the workflow for small TypeScript projects in your daily work.

In this workflow, we'll walk through these topics:

  • What is a tsconfig.json file, and how can you configure a TypeScript project with it?

  • TypeScript declaration files and the typings command-line tool

  • How to write tests running under Mocha, and how to get coverage information using Istanbul

  • How to test in browsers using Karma

Configuring a TypeScript project

The configurations of a TypeScript project can differ for a variety of reasons. But the goals remain clear: we need the editor as well as the compiler to recognize a project and its source files correctly. And tsconfig.json will do the job.

Introduction to tsconfig.json

A TypeScript project does not have to contain a tsconfig.json file. However, most editors rely on this file to recognize a TypeScript project with specified configurations and to provide related features.

A tsconfig.json file accepts three fields: compilerOptions, files, and exclude. For example, a simple tsconfig.json file could be like the following:

{ 
  "compilerOptions": { 
    "target": "es5", 
    "module": "commonjs", 
    "rootDir": "src", 
    "outDir": "out" 
  }, 
  "exclude": [ 
    "out", 
    "node_modules" 
  ] 
} 

Or, if you prefer to manage the source files manually, it could be like this:

{ 
  "compilerOptions": { 
    "target": "es5", 
    "module": "commonjs", 
    "rootDir": "src", 
    "outDir": "out" 
  }, 
  "files": [ 
    "src/foo.ts", 
    "src/bar.ts" 
  ] 
} 

Previously, when we used tsc, we needed to specify the source files explicitly. Now, with tsconfig.json, we can directly run tsc without arguments (or with -w/--watch if you want incremental compilation) in a folder that contains tsconfig.json.

Compiler options

As TypeScript is still evolving, its compiler options keep changing, with new features and updates. An invalid option may break the compilation or editor features for TypeScript. When reading these options, keep in mind that some of them might have been changed.

The following options are useful ones out of the list.

target

target specifies the expected version of JavaScript outputs. It could be es5 (ECMAScript 5), es6 (ECMAScript 6/2015), and so on.

Features (especially ECMAScript polyfills) that are available in different compilation targets vary. For example, before TypeScript 2.1, features such as async/await were available only when targeting ES6.

The good news is that Node.js 6 with the latest V8 engine has supported most ES6 features. And the latest browsers have also great ES6 support. So if you are developing a Node.js application or a browser application that's not required for backward compatibilities, you can have your configuration target ES6.

module

Before ES6, JavaScript had no standard module system. Varieties of module loaders are developed for different scenarios, such as commonjs, amd, umd, system, and so on.

If you are developing a Node.js application or an npm package, commonjs could be the value of this option. Actually, with the help of modern packaging tools such as webpack and browserify, commonjs could also be a nice choice for browser projects as well.

declaration

Enable this option to generate .d.ts declaration files along with JavaScript outputs. Declaration files could be useful as the type information source of a distributed library/framework; it could also be helpful for splitting a larger project to improve compiling performance and division cooperation.

sourceMap

By enabling this option, TypeScript compiler will emit source maps along with compiled JavaScript.

jsx

TypeScript provides built-in support for React JSX (.tsx) files. By specifying this option with value react, TypeScript compiler will compile .tsx files to plain JavaScript files. Or with value preserve, it will output .jsx files so you can post-process these files with other JSX compilers.

noEmitOnError

By default, TypeScript will emit outputs no matter whether type errors are found or not. If this is not what you want, you may set this option to true.

noEmitHelpers

When compiling a newer ECMAScript feature to a lower target version of JavaScript, TypeScript compiler will sometimes generate helper functions such as __extends (ES6 to lower versions), and __awaiter (ES7 to lower versions).

Due to certain reasons, you may want to write your own helper functions, and prevent TypeScript compiler from emitting these helpers.

noImplicitAny

As TypeScript is a superset of JavaScript, it allows variables and parameters to have no type notation. However, it could help to make sure everything is typed.

By enabling this option, TypeScript compiler will give errors if the type of a variable/parameter is not specified and cannot be inferred by its context.

experimentalDecorators*

As decorators, at the time of writing this book, has not yet reached a stable stage of the new ECMAScript standard, you need to enable this option to use decorators.

emitDecoratorMetadata*

Runtime type information could sometimes be useful, but TypeScript does not yet support reflection (maybe it never will). Luckily, we get decorator metadata that will help under certain scenarios.

By enabling this option, TypeScript will emit decorators along with a Reflect.metadata() decorator which contains the type information of the decorated target.

outDir

Usually, we do not want compiled files to be in the same folder of source code. By specifying outDir, you can tell the compiler where you would want the compiled JavaScript files to be.

outFile

For small browser projects, we might want to have all the outputs concatenated as a single file. By enabling this option, we can achieve that without extra build tools.

rootDir

The rootDir option is to specify the root of the source code. If omitted, the compiler would use the longest common path of source files. This might take seconds to understand.

For example, if we have two source files, src/foo.ts and src/bar.ts, and a tsconfig.json file in the same directory of the src folder, the TypeScript compiler will use src as the rootDir, so when emitting files to the outDir (let's say out), they will be out/foo.js and out/bar.js.

However, if we add another source file test/test.ts and compile again, we'll get those outputs located in out/src/foo.js, out/src/bar.js, and out/test/test.js respectively. When calculating the longest common path, declaration files are not involved as they have no output.

Usually, we don't need to specify rootDir, but it would be safer to have it configured.

preserveConstEnums

Enum is a useful tool provided by TypeScript. When compiled, it's in the form of an Enum.member expression. Constant enum, on the other hand, emits number literals directly, which means the Enum object is no longer necessary.

And thus TypeScript, by default, will remove the definitions of constant enums in the compiled JavaScript files.

By enabling this option, you can force the compiler to keep these definitions anyway.

strictNullChecks

TypeScript 2.1 makes it possible to explicitly declare a type with undefined or null as its subtype. And the compiler can now perform more thorough type checking for empty values if this option is enabled.

stripInternal*

When emitting declaration files, there could be something you'll need to use internally but without a better way to specify the accessibility. By commenting this code with /** @internal */ (JSDoc annotation), TypeScript compiler then won't emit them to declaration files.

isolatedModules

By enabling this option, the compiler will unconditionally emit imports for unresolved files.

Note

Options suffixed with * are experimental and might have already been removed when you are reading this book. For a more complete and up-to-date compiler options list, please check out http://www.typescriptlang.org/docs/handbook/compiler-options.html.

Adding source map support

Source maps can help a lot while debugging, no matter for a debugger or for error stack traces from a log.

To have source map support, we need to enable the sourceMap compiler option in tsconfig.json. Extra configurations might be necessary to make your debugger work with source maps.

For error stack traces, we can use the help of the source-map-support package:

$ npm install source-map-support --save

To put it into effect, you can import this package with its register submodule in your entry file:

import 'source-map-support/register'; 

Downloading declarations using typings

JavaScript has a large and booming ecosystem. As the bridge connecting TypeScript and other JavaScript libraries and frameworks, declaration files are playing a very important role.

With the help of declaration files, TypeScript developer can use existing JavaScript libraries with nearly the same experience as libraries written in TypeScript.

Thanks to the efforts of the TypeScript community, almost every popular JavaScript library or framework got its declaration files on a project called DefinitelyTyped. And there has already been a tool called tsd for declaration file management. But soon, people realized the limitation of a single huge repository for everything, as well as the issues tsd cannot solve nicely. Then typings is gently becoming the new tool for TypeScript declaration file management.

Installing typings

typings is just another Node.js package with a command-line interface like TypeScript compiler. To install typings, simply execute the following:

$ npm install typings -g

To make sure it has been installed correctly, you can now try the typings command with argument --version:

$ typings --version
1.x.x

Downloading declaration files

Create a basic Node.js project with a proper tsconfig.json (module option set as commonjs), and a test.ts file:

import * as express from 'express'; 

Without the necessary declaration files, the compiler would complain with Cannot find module express. And, actually, you can't even use Node.js APIs such as process.exit() or require Node.js modules, because TypeScript itself just does not know what Node.js is.

To begin with, we'll need to install declaration files of Node.js and Express:

$ typings install env~node --global
$ typings install express

If everything goes fine, typings should've downloaded several declaration files and saved them to folder typings, including node.d.ts, express.d.ts, and so on. And I guess you've already noticed the dependency relationship existing on declaration files.

Note

If this is not working for you and typings complains with Unable to find "express" ("npm") in the registry then you might need to do it the hard way - to manually install Express declaration files and their dependencies using the following command: $ typings install dt~<package-name> --global

The reason for that is the community might still be moving from DefinitelyTyped to the typings registry. The prefix dt~ tells typings to download declaration files from DefintelyTyped, and --global option tells typings to save these declaration files as ambient modules (namely declarations with module name specified).

typings has several registries, and the default one is called npm (please understand this npm registry is not the npm package registry). So, if no registry is specified with <source>~ prefix or --source option, it will try to find declaration files from its npm registry. This means that typings install express is equivalent to typings install npm~express or typings install express --source npm.

While declaration files for npm packages are usually available on the npm registry, declaration files for the environment are usually available on the env. registry. As those declarations are usually global, a --global option is required for them to install correctly.

Option "save"

typings actually provides a --save option for saving the typing names and file sources to typings.json. However, in my opinion, this option is not practically useful.

It's great to have the most popular JavaScript libraries and frameworks typed, but these declaration files, especially declarations not frequently used, can be inaccurate, which means there's a fair chance that you will need to edit these files yourself.

It would be nice to contribute declarations, but it would also be more flexible to have typings m  managed by source control as part of the project code.

Testing with Mocha and Istanbul

Testing could be an important part of a project, which ensures feature consistency and discovers bugs earlier. It is common that a change made for one feature could break another working part of the project. A robust design could minimize the chance but we still need tests to make sure.

It could lead to an endless discussion about how tests should be written and there are interesting code design techniques such as test-driven development (TDD); though there has been a lot of debates around it, it still worth knowing and may inspire you in certain ways.

Mocha and Chai

Mocha has been one of the most popular test frameworks for JavaScript, while Chaiis a good choice as an assertion library. To make life easier, you may write tests for your own implementations of contents through this book using Mocha and Chai.

To install Mocha, simply run the following command, and it will add mocha as a global command-line tool just like tsc and typings:

$ npm install mocha -g

Chai, on the other hand, is used as a module of a project, and should be installed under the project folder as a development dependency:

$ npm install chai --save-dev

Chai supports should style assertion. By invoking chai.should(), it adds the should property to the prototype of Object, which means you can then write assertions such as the following:

'foo'.should.not.equal('bar'); 
'typescript'.should.have.length(10); 
Writing tests in JavaScript

By executing the command mocha, it will automatically run tests inside the test folder. Before we start to write tests in TypeScript, let's try it out in plain JavaScript and make sure it's working.

Create a file test/starter.js and save it with the following code:

require('chai').should(); 
 
describe('some feature', () => {  
  it('should pass', () => { 
    'foo'.should.not.equal('bar'); 
  }); 
 
  it('should error', () => { 
    (() => { 
      throw new Error(); 
    }).should.throw(); 
  }); 
}); 

Run mocha under the project folder and you should see all tests passing.

Writing tests in TypeScript

Tests written in TypeScript have to be compiled before being run; where to put those files could be a tricky question to answer.

Some people might want to separate tests with their own tsconfig.json:

src/tsconfig.json 
test/tsconfig.json 

They may also want to put output files somewhere reasonable:

out/app/ 
out/test/ 

However, this will increase the cost of build process management for small projects. So, if you do not mind having src in the paths of your compiled files, you can have only one tsconfig.json to get the job done:

src/ 
test/ 
tsconfig.json 

The destinations will be as follows:

out/src/ 
out/test/ 

Another option I personally prefer is to have tests inside of src/test, and use the test folder under the project root for Mocha configurations:

src/ 
src/test/ 
tsconfig.json 

The destinations will be as follows:

out/ 
out/test/ 

But, either way, we'll need to configure Mocha properly to do the following:

  • Run tests under the out/test directory

  • Configure the assertion library and other tools before starting to run tests

To achieve these, we can take advantage of the mocha.opts file instead of specifying command-line arguments every time. Mocha will combine lines in the mocha.opts file with other command-line arguments given while being loaded.

Create test/mocha.opts with the following lines:

--require ./test/mocha.js 
out/test/ 

As you might have guessed, the first line is to tell Mocha to require ./test/mocha.js before starting to run actual tests. And the second line tells Mocha where these tests are located.

And, of course, we'll need to create test/mocha.js correspondingly:

require('chai').should(); 

Almost ready to write tests in TypeScript! But TypeScript compiler does not know how would function describe or it be like, so we need to download declaration files for Mocha:

$ typings install env~mocha --global

Now we can migrate the test/starter.js file to src/test/starter.ts with nearly no change, but removing the first line that enables the should style assertion of Chai, as we have already put it into test/mocha.js.

Compile and run; buy me a cup of coffee if it works. But it probably won't. We've talked about how TypeScript compiler determines the root of source files when explaining the rootDir compiler option. As we don't have any TypeScript files under the src folder (not including its subfolders), TypeScript compiler uses src/test as the rootDir. Thus the compiled test files are now under the out folder instead of the expected out/test.

To fix this, either explicitly specify rootDir, or just add the first non-test TypeScript file to the src folder.

Getting coverage information with Istanbul

Coverage could be important for measuring the quality of tests. However, it might take much effort to reach a number close to 100%, which could be a burden for developers. To balance efforts on tests and code that bring direct value to the product, there would go another debate.

Install Istanbul via npm just as with the other tools:

$ npm install istanbul -g

The subcommand for Istanbul to generate code coverage information is istanbul cover. It should be followed by a JavaScript file, but we need to make it work with Mocha, which is a command-line tool. Luckily, the entry of the Mocha command is, of course, a JavaScript file.

To make them work together, we'll need to install a local (instead of global) version of Mocha for the project:

$ npm install mocha --save-dev

After installation, we'll get the file _mocha under node_modules/mocha/bin, which is the JavaScript entry we were looking for. So now we can make Istanbul work:

$ istanbul cover node_modules/mocha/bin/_mocha

Then you should've got a folder named coverage, and within it the coverage report.

Reviewing the coverage report is important; it can help you decide whether you need to add tests for specific features and code branches.

Testing in real browsers with Karma

We've talked about testing with Mocha and Istanbul for Node.js applications. It is an important topic for testing code that runs in a browser as well.

Karma is a test runner for JavaScript that makes testing in real browsers on real devices much easier. It officially supports the Mocha, Jasmine, and JUnit testing frameworks, but it's also possible for Karma to work with any framework via a simple adapter.

Creating a browser project

A TypeScript application that runs in browsers can be quite different from a Node.js one. But if you know what the project should look like after the build, you should already have clues on how to configure that project.

To avoid introducing too many concepts and technologies not directly related, I will keep things as simple as possible:

  • We're not going to use module loaders such as Require.js

  • We're not going to touch the code packaging process

This means we'll go with separated output files that need to be put into an HTML file with a script tag manually. Here's the tsconfig.json we'll be playing with; notice that we no longer have the module option, set:

{ 
  "compilerOptions": { 
    "target": "es5", 
    "rootDir": "src", 
    "outDir": "out" 
  }, 
  "exclude": [ 
    "out", 
    "node_modules" 
  ] 
} 

Then let's create package.json and install packages mocha and chai with their declarations:

$ npm init
$ npm install mocha chai --save-dev
$ typings install env~mocha --global
$ typings install chai

And to begin with, let's fill this project with some source code and tests.

Create src/index.ts with the following code:

function getLength(str: string): number { 
  return str.length; 
} 

And create src/test/test.ts with some tests:

describe('get length', () => {  
  it('"abc" should have length 3', () => { 
    getLength('abc').should.equal(3); 
  }); 
 
  it('"" should have length 0', () => { 
    getLength('').should.equal(0); 
  }); 
}); 

Again, in order to make the should style assertion work, we'll need to call chai.should() before tests start. To do so, create file test/mocha.js just like we did in the Node.js project, though the code line slightly differs, as we no longer use modules:

chai.should(); 

Now compile these files with tsc, and we've got our project ready.

Installing Karma

Karma itself runs on Node.js, and is available as an npm package just like other Node.js tools we've been using. To install Karma, simply execute the npm install command in the project directory:

$ npm install karma --save-dev

And, in our case, we are going to have Karma working with Mocha, Chai, and the browser Chrome, so we'll need to install related plugins:

$ npm install karma-mocha karma-chai karma-chrome-launcher --save-dev

Before we configure Karma, it is recommended to have karma-cli installed globally so that we can execute the karma command from the console directly:

$ npm install karma-cli -g

Configuring and starting Karma

The configurations are to tell Karma about the testing frameworks and browsers you are going to use, as well as other related information such as source files and tests to run.

To create a Karma configuration file, execute karma init and answer its questions:

  • Testing framework: Mocha

  • Require.js: no

  • Browsers: Chrome (add more if you like; be sure to install the corresponding launchers)

  • Source and test files:

    • test/mocha.js (the file enables should style assertion)

    • out/*.js (source files)

    • out/test/*.js (test files)

  • Files to exclude: empty

  • Watch for changes: yes

Now you should see a karma.conf.js file under the project directory; open it with your editor and add 'chai' to the list of option frameworks.

Almost there! Execute the command karma start and, if everything goes fine, you should have specified browsers opened with the testing results being logged in the console in seconds.

Integrating commands with npm

The npm provides a simple but useful way to define custom scripts that can be run with the npm run command. And it has another advantage - when npm run a custom script, it adds node_modules/.bin to the PATH. This makes it easier to manage project-related command-line tools.

For example, we've talked about Mocha and Istanbul. The prerequisite for having them as commands is to have them installed globally, which requires extra steps other than npm install. Now we can simply save them as development dependencies, and add custom scripts in package.json:

"scripts": { 
  "test": "mocha", 
  "cover": "istanbul cover node_modules/mocha/bin/_mocha" 
}, 
"devDependencies": { 
  "mocha": "latest", 
  "istanbul": "latest" 
} 

Now you can run test with npm run test (or simply npm test), and run cover with npm run cover without installing these packages globally.

Why not other fancy build tools?

You might be wondering: why don't we use a build system such as Gulp to set up our workflow? Actually, when I started to write this chapter, I did list Gulp as the tool we were going to use. Later, I realized it does not make much sense to use Gulp to build the implementations in most of the chapters in this book.

There is a message I want to deliver: balance.

Once, I had a discussion on balance versus principles with my boss. The disagreement was clear: he insisted on controllable principles over subjective balance, while I prefer contextual balance over fixed principles.

Actually, I agree with him, from the point of view of a team leader. A team is usually built up with developers at different levels; principles make it easier for a team to build high-quality products, while not everyone is able to find the right balance point.

However, when the role turns from a productive team member to a learner, it is important to learn and to feel the right balance point. And that's called experience.