I Bet You’re Gonna Like TypeScript

TypeScript, is one of the buzzwords in recent years in the growing web development community, one thing in web technology stack that makes you feel little closer to solid server-side technologies, one thing that you’d find relatively easy to pick up but offers significant values. Received same response from many others during my talks to several development teams. The main reason why you would find it rather easier is the new features are new to JavaScript but for programmers are already familiar with most of the concepts (in .NET, Java or any other OOP languages) such as modules, classes, interfaces, static typing, etc. Read further to understand more about what TypeScript is and what it solves.

What is TypeScript?

A superset of JavaScript. All the features of JavaScript are valid TypeScript and a JavaScript file (abc.js) is a valid TypeScript file when you rename its extension to ts (abc.ts). “.ts” is the file extension of TypeScript file.
Open source. It is an open source project maintained by Microsoft. Although it was introduced in 2012, taking a center stage now as many industry leaders have embraced it to build their core frameworks such as Google team use for Angular2, Telerik team for NativeScript, are few to mention.
ES5 + ES6 + Types + more. In addition to current JavaScript (ECMAScript 5 / ES5, language spec maintained by the body ECMA since 2009) language features and constructs, TypeScript supports next generation JavaScript (ES6 / 2015, next gen. language spec) features for writing better, clean, elegant, structured, object oriented code; optional type system, static typing (duck typing) that improves quality of code and agility; powerful tooling and intellisense support to increases developer productivity.
typescriptoverview
Thing of development time. All the perks TypeScript offers are thing of development time. You would write clean TypeScript code, leverage the tooling support during development, store ts files into source control, use ts compiler through Visual Studio (any other IDE) or build tasks to convert ts code to plain JavaScript which will be packaged, hosted and executed at run time either in the browser or server (Node.js). The compiled JavaScript code is still very much readable and understandable except little bit extra or translated code generated by TypeScript compiler. I’ll explain how TypeScript features get translated into JavaScript later in another blogpost.

typescript

What does TypeScript solve?

While we get to the answer, it is important to understand the common challenges with JavaScript in medium to large scale web application development as TypeScript solves majority of them eventually. Seasoned JavaScript developers love the power, flexibility, dynamism and asynchrony nature of the language, however following common problems with JavaScript affect code quality and maintainability significantly – harder to maintain as applications get bigger.

Lack of language constructs. JavaScript is a powerful, functional and dynamic typed programming language but ES5 version of current JavaScript features include simple set of constructs. Building and maintaining large code base with very few (dynamic) types, no static typing, no easy way to structure and modularize code base, no easier way to implement object oriented concepts is a nightmare. While web has evolved to build entire application using JavaScript and browser vendors are taking baby steps to implement ES 2015 features.
TypeScript solves it by providing rich set of ES 2015 constructs and features that allows you to write better, elegant, well organized, highly readable, scalable and maintainable code which is very important for large size applications .

Complex implementation of key features. You might know JavaScript is not class-based language, still you can implement inheritance through the concept of Prototype Chain that enables to create relationships between objects by attaching behaviors of one object (child) to Prototype of another. Closure provides a way to encapsulate object members to express object oriented programming nature. “this” keyword used in a function can refer members outside the function (same as accessing a class member from an instance method in other OOPs languages) but the value of members varies depends on the context where it is executed. They are important concepts in JavaScript but most misunderstood and incorrect usage of them leads to unpredictable results, memory leakage and other coding errors.
TypeScript solves it by providing sugar coated modules, namespaces, classes, interfaces, access modifiers, etc. in the same way you are familiar in other OOPs languages which allows to structure, maintain and collaborate the components better and eliminates the above stated confusions for any developer. The arrow (=>) function solves the above mentioned problem with “this” keyword by preserving the current context into another object and also it is a shorthand syntax to define anonymous functions.

Dynamic Typing. Dynamic type system provides the flexibility but limits to detect common errors (assignment of incompatible type objects) during compile time.
TypeScript solves it by optional static typing, also called as duck typing, means it just enforces to check the shape of an object (not the origin) for the compatibility. Type-checking at compile time prevents incompatible type assignments, improves productivity, code refactoring and is a living form of documentation. Apart from basic types (Number, String, Boolean), supported other types Any, String Literal, Union, Intersection, Enum and related features Type alias and Type guards are very useful addition to the language. The optional type systems helps to migrate existing JavaScript files in phased manner by either no typing or using Any type.

TypeScript helped to capture several issues during build and improved refactoring efforts in Angular 2 development.

– Brad Green, Eng. Director at Google praised TypeScript in a podcast.

Supported IDEs

TypeScript plugins are available for all major IDEs such as Visual Studio, Visual Studio Code, Eclipse, Sublime, WebStorm, etc. You can find the installer you want at this link.

Debugging

Since the generated output JavaScript runs on browser (for web), you can directly debug JavaScript code if comfortable with core concepts. It is also possible to debug TypeScript code through Source maps.

Declaration files

If you are building applications using TypeScript and either you are consuming external libraries or others using your libraries need the declaration files (*.d.ts) to export and refer shape of the code, they are inputs for the process of type inference and type-checking. TypeScript compiler generates declaration files for objects that are marked “export”.

Compiler configuration

You can setup compiler for targeted ECMAScript version, module system, need of declaration files, map files, removing commented lines and so on in either tsconfig.json at root path or project settings in Visual Studio.

Sample TypeScript Code for AngularJS Controller
namespace Cricket {
    class ScorecardController {
        public match: Model.Match;
        static $inject = ["ScorecardService"];
        constructor(private scorecardService: IScorecardService) {
            this.initialize();
        }
        initialize() {
            this.scorecardService.getScorecard().then((match: Model.Match) => {
                this.match = match;
            });
        }        
    }
    angular.module('Cricket').controller('ScorecardController', ScorecardController);
}

Note that the article is not intend to cover explaining TypeScript features in detail, you can refer them in the official handbook, my GitHub demo project and may expect few more posts from me later for some key features.

Hope you enjoyed reading this post and find it useful. I love to hear your feedback, you may write your comments down below and/ or share it.