TypeScript Design Patterns - Vilic Vane - E-Book

TypeScript Design Patterns E-Book

Vilic Vane

0,0
33,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Boost your development efficiency by learning about design patterns in TypeScript

About This Book

  • This step-by-step guide will would demonstrate all the important design patterns in practice
  • This book is the only documentation on the market focusing on design patterns in TypeScript
  • This book is packed with rich examples that will improve your efficiency and encourage code reuse

Who This Book Is For

If you are a TypeScript developer, this book is for you. No knowledge of design patterns is required to read this book.

What You Will Learn

  • Understand the challenges and implications of developing an enterprise application
  • Install and configure the necessary tools in order to start developing an application
  • Identify the challenges when developing an application
  • Apply GoF patterns in an application with a testing approach
  • Use and utilize design patterns while developing a TypeScript application or during JavaScript application development
  • Reference to SOLID principles and what their benefits do to your projects
  • Apply various principles in a TypeScript application
  • Improve code quality and development speed

In Detail

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.

Style and approach

In this book, design patterns are explained in a step-by-step manner. All the major patterns covered will improve your understanding of TypeScript and the patterns associated with TypeScript.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 260

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

TypeScript Design Patterns
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Tools and Frameworks
Installing the prerequisites
Installing Node.js
Installing TypeScript compiler
Choosing a handy editor
Visual Studio Code
Configuring Visual Studio Code
Opening a folder as a workspace
Configuring a minimum build task
Sublime Text with TypeScript plugin
Installing Package Control
Installing the TypeScript plugin
Other editor or IDE options
Atom with the TypeScript plugin
Visual Studio
WebStorm
Getting your hands on the workflow
Configuring a TypeScript project
Introduction to tsconfig.json
Compiler options
target
module
declaration
sourceMap
jsx
noEmitOnError
noEmitHelpers
noImplicitAny
experimentalDecorators*
emitDecoratorMetadata*
outDir
outFile
rootDir
preserveConstEnums
strictNullChecks
stripInternal*
isolatedModules
Adding source map support
Downloading declarations using typings
Installing typings
Downloading declaration files
Option "save"
Testing with Mocha and Istanbul
Mocha and Chai
Writing tests in JavaScript
Writing tests in TypeScript
Getting coverage information with Istanbul
Testing in real browsers with Karma
Creating a browser project
Installing Karma
Configuring and starting Karma
Integrating commands with npm
Why not other fancy build tools?
Summary
2. The Challenge of Increasing Complexity
Implementing the basics
Creating the code base
Defining the initial structure of the data to be synchronized
Getting data by comparing timestamps
Two-way synchronizing
Things that went wrong while implementing the basics
Passing a data store from the server to the client does not make sense
Making the relationships clear
Growing features
Synchronizing multiple items
Simply replacing data type with an array
Server-centered synchronization
Synchronizing from the server to the client
Synchronizing from client to server
Synchronizing multiple types of data
Supporting multiple clients with incremental data
Updating the client side
Updating server side
Supporting more conflict merging
New data structures
Updating client side
Updating the server side
Things that go wrong while implementing everything
Piling up similar yet parallel processes
Data stores that are tremendously simplified
Getting things right
Finding abstraction
Implementing strategies
Wrapping stores
Summary
3. Creational Design Patterns
Factory method
Participants
Pattern scope
Implementation
Consequences
Abstract Factory
Participants
Pattern scope
Implementation
Consequences
Builder
Participants
Pattern scope
Implementation
Consequences
Prototype
Singleton
Basic implementations
Conditional singletons
Summary
4. Structural Design Patterns
Composite Pattern
Participants
Pattern scope
Implementation
Consequences
Decorator Pattern
Participants
Pattern scope
Implementation
Classical decorators
Decorators with ES-next syntax
Consequences
Adapter Pattern
Participants
Pattern scope
Implementation
Consequences
Bridge Pattern
Participants
Pattern scope
Implementation
Consequences
Façade Pattern
Participants
Pattern scope
Implementation
Consequences
Flyweight Pattern
Participants
Pattern scope
Implementation
Consequences
Proxy Pattern
Participants
Pattern scope
Implementation
Consequences
Summary
5. Behavioral Design Patterns
Chain of Responsibility Pattern
Participants
Pattern scope
Implementation
Consequences
Command Pattern
Participants
Pattern scope
Implementation
Consequences
Memento Pattern
Participants
Pattern scope
Implementation
Consequences
Iterator Pattern
Participants
Pattern scope
Implementation
Simple array iterator
ES6 iterator
Consequences
Mediator Pattern
Participants
Pattern scope
Implementation
Consequences
Summary
6. Behavioral Design Patterns: Continuous
Strategy Pattern
Participants
Pattern scope
Implementation
Consequences
State Pattern
Participants
Pattern scope
Implementation
Consequences
Template Method Pattern
Participants
Pattern scope
Implementation
Consequences
Observer Pattern
Participants
Pattern scope
Implementation
Consequences
Visitor Pattern
Participants
Pattern scope
Implementation
Consequences
Summary
7. Patterns and Architectures in JavaScript and TypeScript
Promise-based web architecture
Promisifying existing modules or libraries
Views and controllers in Express
Abstraction of responses
Abstraction of permissions
Expected errors
Defining and throwing expected errors
Transforming errors
Modularizing project
Asynchronous patterns
Writing predictable code
Asynchronous creational patterns
Asynchronous middleware and hooks
Event-based stream parser
Summary
8. SOLID Principles
Single responsibility principle
Example
Choosing an axis
Open-closed principle
Example
Abstraction in JavaScript and TypeScript
Refactor earlier
Liskov substitution principle
Example
The constraints of substitution
Interface segregation principle
Example
Proper granularity
Dependency inversion principle
Example
Separating layers
Summary
9. The Road to Enterprise Application
Creating an application
Decision between SPA and "normal" web applications
Taking team collaboration into consideration
Building and testing projects
Static assets packaging with webpack
Introduction to webpack
Bundling JavaScript
Loading TypeScript
Splitting code
Loading other static assets
Adding TSLint to projects
Integrating webpack and tslint command with npm scripts
Version control
Git flow
Main branches
Supporting branches
Feature branches
Release branches
Hotfix branches
Summary of Git flow
Pull request based code review
Configuring branch permissions
Comments and modifications before merge
Testing before commits
Git hooks
Adding pre-commit hook automatically
Continuous integration
Connecting GitHub repository with Travis-CI
Deployment automation
Passive deployment based on Git server side hooks
Proactive deployment based on timers or notifications
Summary

TypeScript Design Patterns

TypeScript Design Patterns

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: August 2016

Production reference: 1240816

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78528-083-2

www.packtpub.com

Credits

Author

Vilic Vane

Copy Editor

Safis Editing

Reviewer

Wander Wang

Project Coordinator

 Suzanne Coutinho

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

AcquisitionEditor

Denim Pinto

Indexer

Rekha Nair

Content Development Editor

Nikhil Borkar

Graphics

Jason Monteiro

Technical Editor

Hussain Kanchwala

Production Coordinator

Aparna Bhagat

About the Author

Vilic Vane is a JavaScript engineer with over 8 years of experience in web development. He started following the TypeScript project since it went public, and he’s also a contributor of the project. He is now working at Ruff, a startup company building an IoT platform that runs JavaScript on embedded devices.

I want to thank the editors and reviewers, including Wander Wang, for their efforts that made this book possible. I also want to thank my girlfriend, Emi, for not pissing me off when she came for me from her school 1,400 km away but could only have a takeout with me in my apartment due to my always-about-to-start-writing condition.

About the Reviewer

Wander Wang is working at Egret Technology Co., Ltd. as the chief architect of Egret Engine. He also works as a part-time teacher in the School of Software Engineering at Beijing University of Technology. Wang has 7 years of experience in developing web and mobile games, and he currently focuses on the language research and extension of TypeScript. Egret Engine is a popular HTML5 game engine written in TypeScript. There are more than 80,000 developers worldwide who build their web or mobile games on the top of Egret Engine. Wang is also interested in technologies such as React, React-Native, and Electron, and so on.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

It wasn’t a long time ago that many JavaScript engineers or, most of the time, web frontend engineers, were still focusing on solving detailed technical issues, such as how to lay out specific content cross-browsers and how to send requests cross-domains.

At that time, a good web frontend engineer was usually expected to have notable experience on how detailed features can be implemented with existing APIs. Only a few people cared about how to write application-scale JavaScript because the interaction on a web page was really simple and no one wrote ASP in JavaScript.

However, the situation has changed tremendously. JavaScript has become the only language that runs everywhere, cross-platform and cross-device. In the main battlefield, interactions on the Web become more and more complex, and people are moving business logic from the backend to the frontend. With the growth of the Node.js community, JavaScript is playing a more and more important roles in our life.

I am currently working for an IoT company called Ruff that builds a platform for JavaScript to write applications run on embedded devices. You might have seen a fake book cover in the title of Writing Device Drivers in JavaScript, but that is actually a part of what we do.

The boom of JavaScript, however, makes people realize that the language itself might not be powerful enough for applications on a larger scale. While we enjoy the flexibility of the language, we suffer from its lack of static-type information; for instance, consider the following:

No static type checking: We have to rely on debugging or tests to get rid of simple errors that could be eliminated when the code is written.Refactoring is a pain: Basically, what the IDEs or editors can do about JavaScript code is renaming local variables or exported module functions at best.Understanding code is difficult: When you grasp a piece of code, you might have to look around and manually search for references just to figure out which properties an object has and what types of property they are. This happens to our own code as well.

Compared to tools such as ESLint and even Flow, which only partially solve the problems, TypeScript does a really good job while it is still sticking to the ECMAScript standard.

TypeScript is indeed an awesome tool for JavaScript. Unfortunately, intelligence is still required to write actually robust, maintainable, and reusable code. But wait, doesn’t the intelligence part involve the true value of our work?

We might all have had trouble finding clues to mysterious bugs, or squeezed our head thinking about how we can add new features to the existing code base. Some of us, with experience and intuition built over the years, may directly come up with a design that’s not bad. For these people, getting through the common design patterns can help gain knowledge of what people have already catalogued over years in the industry or be better understood when discussing software designs with others. For people who have less experience, learning common design patterns may be a more straightforward approach to creating code that’s beautifully designed.

What this book covers

Chapter 1, Tools and Frameworks, provides a brief introduction to tools and frameworks that will be used through this book, including installing a TypeScript compiler, preparing an editor, and a basic workflow.

Chapter 2, The Challenge of Increasing Complexity, starts with a simple server-client synchronizing implementation; we then expand its features and see how things can gain undesired complexity and how that complexity can be reduced.

Chapter 3, Creational Design Patterns, catalogs five common creational design patterns, the Factory Method, Abstract Factory, Builder, Prototype, and Singleton patterns.

Chapter 4, Structural Design Patterns, catalogs seven common structural design patterns, the Composite, Decorator, Adapter, Bridge, Façade, Flyweight, and Proxy patterns.

Chapter 5, Behavioral Design Patterns, catalogs five common behavioral design patterns, the Chain of Responsibility, Command, Memento, Iterator, and Mediator patterns.

Chapter 6, Behavioral Design Patterns: Continuous, catalogs another four common behavioral design patterns, the Strategy, State, Template Method, Observer, and Visitor patterns.

Chapter 7, Patterns and Architectures in JavaScript and TypeScript, takes a look at the patterns and architectures that closely relate to the language (JavaScript or TypeScript) and its application, including asynchronous programming, module organization, error handling, permission abstraction, and so on.

Chapter 8, SOLID Principles, explains the well-known SOLID principles and how they can benefit a project and keep it healthy over time.

Chapter 9, The Road to Enterprise Application, guides readers to build the complete workflow of an application that is ready to scale, including testing and continuous integration.

What you need for this book

It is possible to read through this entire book without installing anything. But it is recommended that you have a handy editor and TypeScript compiler installed to get your hands dirty. Please refer to Chapter 1, Tools and Frameworks, for the detailed preparation of tools, including Node.js, a TypeScript compiler, declaration manager, and a nice editor or IDE.

Though this book does not require the reader to have a knowledge of design patterns, it's not a book that teaches basic TypeScript syntax. If you are not yet familiar with TypeScript, please walk through the TypeScript Handbook before reading Chapter 2, The Challenge of Increasing Complexity.

Who this book is for

If you are a TypeScript developer, this book is for you. No knowledge of design patterns is required to read this book.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Save the following code to file test.ts."

A block of code is set as follows:

require('chai').should();

Any command-line input or output is written as follows:

$ tsc test.ts

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Without the necessary declaration files, the compiler would complain Cannot find module express."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/TypeScript-Design-Patterns/. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. Tools and Frameworks

We could always use the help of real code to explain the design patterns we'll be discussing. In this chapter, we'll have a brief introduction to the tools and frameworks that you might need if you want to have some practice with complete working implementations of the contents of this book.

In this chapter, we'll cover the following topics:

Installing Node.js and TypeScript compilerPopular editors or IDEs for TypeScriptConfiguring a TypeScript projectA basic workflow that you might need to play with your own implementations of the design patterns in this book

Installing the prerequisites

The contents of this chapter are expected to work on all major and up-to-date desktop operating systems, including Windows, OS X, and Linux.

As Node.js is widely used as a runtime for server applications as well as frontend build tools, we are going to make it the main playground of code in this book.

TypeScript compiler, on the other hand, is the tool that compiles TypeScript source files into plain JavaScript. It's available on multiple platforms and runtimes, and in this book we'll be using the Node.js version.

Installing Node.js

Installing Node.js should be easy enough. But there's something we could do to minimize incompatibility over time and across different environments:

Version: We'll be using Node.js 6 with npm 3 built-in in this book. (The major version of Node.js may increase rapidly over time, but we can expect minimum breaking changes directly related to our contents. Feel free to try a newer version if it's available.)Path: If you are installing Node.js without a package manager, make sure the environment variable PATH is properly configured.

Open a console (a command prompt or terminal, depending on your operating system) and make sure Node.js as well as the built-in package manager npm is working:

$ node -v 6.x.x $ npm -v 3.x.x

Installing TypeScript compiler

TypeScript compiler for Node.js is published as an npm package with command line interface. To install the compiler, we can simply use the npm install command:

$ npm install typescript -g

Option -g means a global installation, so that tsc will be available as a command. Now let's make sure the compiler works:

$ tsc -v Version 2.x.x

Note

You may get a rough list of the options your TypeScript compiler provides with switch -h. Taking a look into these options may help you discover some useful features.

Before choosing an editor, let's print out the legendary phrase:

Save the following code to file test.ts: function hello(name: string): void {        console.log(`hello, ${name}!`);       }              hello('world'); Change the working directory of your console to the folder containing the created file, and compile it with tsc: $ tsc test.tsWith luck, you should have the compiled JavaScript file as test.js. Execute it with Node.js to get the ceremony done:$ node test.jshello, world!

Here we go, on the road to retire your CTO.

Choosing a handy editor

A compiler without a good editor won't be enough (if you are not a believer of Notepad). Thanks to the efforts made by the TypeScript community, there are plenty of great editors and IDEs ready for TypeScript development.

However, the choice of an editor could be much about personal preferences. In this section, we'll talk about the installation and configuration of Visual Studio Code and Sublime Text. But other popular editors or IDEs for TypeScript will also be listed with brief introductions.

Visual Studio Code

Visual Studio Code is a free lightweight editor written in TypeScript. And it's an open source and cross-platform editor that already has TypeScript support built-in.

You can download Visual Studio Code from https://code.visualstudio.com/ and the installation will probably take no more than 1 minute.

The following screenshot shows the debugging interface of Visual Studio Code with a TypeScript source file:

Configuring Visual Studio Code

As Code already has TypeScript support built-in, extra configurations are actually not required. But if the version of TypeScript compiler you use to compile the source code differs from what Code has built-in, it could result in unconformity between editing and compiling.

To stay away from the undesired issues this would bring, we need to configure TypeScript SDK used by Visual Studio Code manually:

Press F1, type Open User Settings , and enter. Visual Studio Code will open the settings JSON file by the side of a read-only JSON file containing all the default settings.Add the field typescript.tsdk with the path of the lib folder under the TypeScript package we previously installed:

1. Execute the command npm root -g in your console to get the root of global Node.js modules.

2. Append the root path with /typescript/lib as the SDK path.

Note

You can also have a TypeScript package installed locally with the project, and use the local TypeScript lib path for Visual Studio Code. (You will need to use the locally installed version for compiling as well.)

Opening a folder as a workspace

Visual Studio Code is a file- and folder-based editor, which means you can open a file or a folder and start work.

But you still need to properly configure the project to take the best advantage of Code. For TypeScript, the project file is tsconfig.json, which contains the description of source files and compiler options. Know little about tsconfig.json? Don't worry, we'll come to that later.

Here are some features of Visual Studio Code you might be interested in:

Tasks: Basic task integration. You can build your project without leaving the editor.Debugging: Node.js debugging with source map support, which means you can debug Node.js applications written in TypeScript.Git: Basic Git integration. This makes comparing and committing changes easier.

Configuring a minimum build task

The default key binding for a build task is Ctrl + Shift + B or cmd + Shift + B on OS X. By pressing these keys, you will get a prompt notifying you that no task runner has been configured. Click Configure Task Runner and then select a TypeScript build task template (either with or without the watch mode enabled). A tasks.json file under the .vscode folder will be created automatically with content similar to the following:

{ "version": "0.1.0", "command": "tsc", "isShellCommand": true, "args": ["-w", "-p", "."], "showOutput": "silent", "isWatching": true, "problemMatcher": "$tsc-watch" }

Now create a test.ts file with some hello-world code and run the build task again. You can either press the shortcut we mentioned before or press Ctrl/Cmd + P, type task tsc , and enter.

If you were doing things correctly, you should be seeing the output test.js by the side of test.ts.

There are some useful configurations for tasking that can't be covered. You may find more information on the website of Visual Studio Code: https://code.visualstudio.com/.

From my perspective, Visual Studio Code delivers the best TypeScript development experience in the class of code editors. But if you are not a fan of it, TypeScript is also available with official support for Sublime Text.

Sublime Text with TypeScript plugin

Sublime Text is another popular lightweight editor around the field with amazing performance.

The following image shows how TypeScript IntelliSense works in Sublime Text:

The TypeScript team has officially built a plugin for Sublime Text (version 3 preferred), and you can find a detailed introduction, including useful shortcuts, in their GitHub repository here: https://github.com/Microsoft/TypeScript-Sublime-Plugin.

Note

There are still some issues with the TypeScript plugin for Sublime Text. It would be nice to know about them before you start writing TypeScript with Sublime Text.

Installing Package Control

Package Control is de facto package manager for Sublime Text, with which we'll install the TypeScript plugin.

If you don't have Package Control installed, perform the following steps:

Click Preferences > Browse Packages..., it opens the Sublime Text packages folder.Browse up to the parent folder and then into the Install Packages folder, and download the file below into this folder: https://packagecontrol.io/Package%20Control.sublime-packageRestart Sublime Text and you should now have a working package manager.

Now we are only one step away from IntelliSense and refactoring with Sublime Text.

Installing the TypeScript plugin

With the help of Package Control, it's easy to install a plugin:

Open the Sublime Text editor; press Ctrl + Shift + P for Windows and Linux or Cmd + Shift + P for OS X.Type Install Package in the command palette, select Package Control: Install Package and wait for it to load the plugin repositories.Type TypeScript and select to install the official plugin.

Now we have TypeScript ready for Sublime Text, cheers!

Like Visual Studio Code, unmatched TypeScript versions between the plugin and compiler could lead to problems. To fix this, you can add the field "typescript_tsdk" with a path to the TypeScript lib in the Settings - User file.

Other editor or IDE options

Visual Studio Code and Sublime Text are recommended due to their ease of use and popularity respectively. But there are many great tools from the editor class to full-featured IDE.

Though we're not going through the setup and configuration of those tools, you might want to try them out yourself, especially if you are already working with some of them.

However, the configuration for different editors and IDEs (especially IDEs) could differ. It is recommended to use Visual Studio Code or Sublime Text for going through the workflow and examples in this book.

Atom with the TypeScript plugin

Atom is a cross-platform editor created by GitHub. It has a notable community with plenty of useful plugins, including atom-typescript. atom-typescript is the result of the hard work of Basarat Ali Syed, and it's used by my team before Visual Studio Code. It has many handy features that Visual Studio Code does not have yet, such as module path suggestion, compile on save, and so on.

Like Visual Studio Code, Atom is also an editor based on web technologies. Actually, the shell used by Visual Studio Code is exactly what's used by Atom: Electron, another popular project by GitHub, for building cross-platform desktop applications.

Atom is proud of being hackable, which means you can customize your own Atom editor pretty much as you want.

Then you may be wondering why we turned to Visual Studio Code. The main reason is that Visual Studio Code is being backed by the same company that develops TypeScript, and another reason might be the performance issue with Atom.

But anyway, Atom could be a great choice for a start.

Visual Studio

Visual Studio is one of the best IDEs in the market. And yet it has, of course, official TypeScript support.

Since Visual Studio 2013, a community version is provided for free to individual developers, small companies, and open source projects.

If you are looking for a powerful IDE of TypeScript on Windows, Visual Studio could be a wonderful choice. Though Visual Studio has built-in TypeScript support, do make sure it's up-to-date. And, usually, you might want to install the newest TypeScript tools for Visual Studio.

WebStorm

WebStorm is one of the most popular IDEs for JavaScript developers, and it has had an early adoption to TypeScript as well.

A downside of using WebStorm for TypeScript is that it is always one step slower catching up to the latest version compared to other major editors. Unlike editors that directly use the language service provided by the TypeScript project, WebStorm seems to have its own infrastructure for IntelliSense and refactoring. But, in return, it makes TypeScript support in WebStorm more customizable and consistent with other features it provides.

If you decide to use WebStorm as your TypeScript IDE, please make sure the version of supported TypeScript matches what you expect (usually the latest version).

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 toolHow to write tests running under Mocha, and how to get coverage information using IstanbulHow 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: