Why program in TypeScript

A little bit of a JavaScript history

In May of 1995, after 10 days of hard work, Brendan Eich wrote the JavaScript programming language. This scripting language didn’t need a compiler and was meant to be used in the web browser Netscape Navigator. No compilers were needed for deploying a program written in JavaScript in the browser. Adding a tag with the JavaScript sources (or a reference to the file with sources) would instruct the browser to load and parse the code and execute it in the browser’s JavaScript engine. People enjoyed the simplicity of the language – no need to declare types of variables, no need to use any tools – just write your code in a plain text editor and use it in a web page.

JavaScript is a dynamic language, which would give additional freedom for software developers. No need to declare properties of an object as the JavaScript engine would create the property during the runtime if the object didn’t already have it.

Actually, there’s no way to declare the type of a variable. The JavaScript engine will guess the type based on the assigned value (e.g. var x = 123 would mean that x is a number). If later on, the script would have an assignment x = 678, the type of x would automatically change from a number to string.

Did you really want to change the type of x or it’s a mistake? You’ll know it only during the runtime as there is no compiler to warn you about it.

JavaScript is a very forgiving language, which is not a shortcoming if the codebase is small and you’re the only person working on this project. Most likely, you remember that x supposed to be a number, and you don’t need any help with this. And of course, you’ll work your current employer forever so the variable x is never forgotten.

Over the years, JavaScript became super popular and de facto standard programming language of the web. But if 20 years ago we’d use JavaScript just to display web pages with some content and make these pages interactive, today we develop complex web apps that contain thousands of lines of code developed by teams of developers. And you know what? Not everyone in your team remembers that x supposed to be a number.

To be more productive, software developers could help from the tooling like IDE with auto-complete features, easy refactoring et al. But how an IDE can help you with refactoring if the language allows complete freedom in adding properties to objects and changing types on the fly?

Everyone realized that replacing JavaScript in all different browsers with another language is not realistic, so new languages were created. They were more tooling-friendly during development, but the program would still have to be converted to JavaScript before deployment so every browser would support them. TypeScript is one of such languages, and let’s see what makes it stand out.

Why program in TypeScript

TypeScript is a compile-to-JavaScript language, which was released by Microsoft as an open source project in 2012. A program written in TypeScript has to be transpiled into JavaScript first, and then it can be executed in the browser or a standalone JavaScript engine.

The difference between transpiling and compiling is that the latter turns the source code of a program into bytecode or machine code, whereas the former converts the program from one language to another, e.g. from TypeScript to JavaScript. But in TypeScript community, the word compile is more popular, and I’ll use it to describe the process of conversion of the TypeScript code into JavaScript.

You may wonder, why go through a hassle of writing a program in TypeScript and then compiling it into JavaScript, if you could write this program in JavaScript in the first place? To answer this question, let’s look at the TypeScript from a very high-level perspective.

TypeScript is a superset of JavaScript, and you can take any JavaScript file, e.g. myProgram.js, change its name extension from .js to .ts, and most likely, the file myProgram.ts becomes a valid TypeScript program. I say most likely, because your JavaScript code may have hidden type-related bugs, you may dynamically change the types of object properties or add new ones after the object was declared and some other things that can be revealed only after your JavaScript code is compiled.
In general, the word superset means that it contains everything that the set has plus something else. The main addition to the “JavaScript set” is that TypeScript also supports static typing whereas JavaScript supports only dynamic typing. Here, the word typing refers to assigning types to program variables.

In programming languages with static typing, a type must be assigned to a variable before you can use it. In TypeScript, you can declare a variable of a certain type, and any attempt to assign to it a value of a different type results in a compilation error. This is not the case in JavaScript, which doesn’t know about the types of your program variables until the runtime. Even in the running program, you can change the type of a variable just by assigning to it a value of different type.

For example, if you declare a variable as a string, trying to assign a numeric value to it will result in the compile-time error.

let customerId: string
customerId = 123; // compile-time error

JavaScript decides on the variable type during the runtime, and the type can be dynamically changed as in the following example:

let customerId = "A15BN"; // OK, customerId is a string
customerId = 123; // OK, from now on it's a number

Now let’s consider a JavaScript function that applies a discount to a price. It has two arguments and both must be numbers.

function getFinalPrice(price, discount) {
   return price - price / discount;
}

How do you know that the arguments must be numbers? First of all, you authored this function some time ago and having an exceptional memory, you may just remember all types of all functions arguments. Secondly, you used descriptive names of the arguments that hint their types. Thirdly, you could guess the types by reading the function code.

This is a pretty simple function, but let’s say someone (not you) would invoke this function by providing a discount as a string, this function would print NaN during runtime.

console.log(getFinalPrice( 100, "10%")); // prints NaN

This is an example of a runtime error caused by the wrong use of a function. In TypeScript, you could provide the types for the function arguments, and such a runtime error would never happen. If someone would try to invoke the function with a wrong type of an argument, this error would be caught as you were typing. Let’s see it in action.

The official TypeScript web page is located at http://www.typescriptlang.org. It offers the language documentation and a playground, where you could enter the code snippets in TypeScript, which would be immediately compiled into JavaScript.

Follow this link, and you’ll see our code snippet in the TypeScript playground, with the squiggly red line under the “10%”. If you hover the mouse over the erroneous code, you’ll see a prompt explaining the error as shown in the screenshot below.

This error is caught by the TypeScript static code analyzer as you type even before you compile this code with tsc. Moreover, if you specify the variable types, your editor or IDE would offer the auto-complete feature suggesting you the argument names and types of the getFinalPrice() function.

Isn’t it nice that errors are caught before runtime? We think so. The vast majority of the developers with the background in such languages as Java, C++, C# take it for granted that the errors are caught during compile time, and this is one of the main reasons why they like TypeScript.

NOTE: There are two types of programming errors – those that are immediately reported by the tools as you type, and those that are reported by the users of your program. Programming in TypeScript substantially decreases the number of the latter.

Still, some of the hard-core JavaScript developers say that TypeScript slows them down by requiring to declare types, and in JavaScript, they’d be more productive. But the majority of the web developers are not JavaScript ninjas and can appreciate a helping hand offered by TypeScript.

There are more than a hundred programming languages that are compiled to JavaScript, but what makes TypeScript stand out is that its creators follow the ECMAScript standards and implement the upcoming JavaScript features a lot faster than Web browsers vendors.

You can find the current proposals of the new ECMAScript features here. A proposal has to go through several stages to be included in the final version of the next ECMAScript spec. If a proposal makes it to Stage 3, most likely it’s included in the latest version of TypeScript.

In the Summer of 2017, the async and await keywords were included into the ECMAScript specification ES2017, a.k.a. ES8. It took more than a year for major browsers to start supporting these keywords. But TypeScript supported them since November of 2015. This means that TypeScript developers could start using these keywords about three years earlier than those who waited for the browsers’ support.

And the best part is that you can use the future JavaScript syntax in today’s TypeScript code and compile it down to the older JavaScript syntax (e.g. ES5) supported by all browsers!

Having said that, we’d like to make a clear distinction between the syntax described in the latest ECMAScript specifications, and the syntax that’s unique to TypeScript. That’s why we recommend you to read the Appendix A first, so you know where ECMAScript ends and TypeScript begins.

Although JavaScript engines do a decent job of guessing the types of variables by their values, development tools have a limited ability to help you without knowing the types. In mid- and large-size applications, this JavaScript shortcoming lowers the productivity of software developers.

The generated JavaScript code is easy to read, and it looks like hand-written code.

TypeScript follows the latest specifications of ECMAScript and adds types, interfaces, decorators, class member variables (fields), generics, enums, the keywords public, protected, and private and more. Check the TypeScript roadmap to see what’s available and what’s coming in the future releases of TypeScript.

Five facts about TypeScript
***************
1. The core developer of TypeScript is Andres Hejlsberg, who also designed Turbo Pascal and Delphi, and is the lead architect of C# at Microsoft.

2. At the end of 2014, Google approached Microsoft asking if they could introduce decorators in TypeScript so this language could be used for developing of the Angular 2 framework. Microsoft agreed, and this gave a tremendous boost to the TypeScript popularity given the fact that hundreds of thousands of developers use Angular.

3. As of September of 2018, the TypeScript compiler had more than three million downloads per week from npmjs.org, and this is not the only TypeScript repository. In April of 2019, it was about 6 million per week. For current statistics, visit this page.

4. As per Redmonk, a respectful software analytics firm, TypeScript came 12th in the programming language rankings chart in January of 2019.

5. According to the StackOverflow Survey 2019, TypeScript is the third (tied for 2nd) most loved language.
***************

And one more thing. Some JavaScript developers are still in denial and say, “If I’ll be programming in TypeScript, I’ll need to introduce an extra step between writing code and seeing it running – the compilation.” When I hear such an argument, I want to ask, “Do you really want to stick to the ES5 version of JavaScript ignoring all the latest syntax introduced by ES6, 7, 8, and 9? If not, then you’ll have the compilation step in your workflow anyway – compile a newer JavaScript into the ES5 syntax.”

To continue getting familiar with TypeScript, read about the structural type system here.

10 thoughts on “Why program in TypeScript

  1. Wow, I didn’t know it’s Andres Hejlsberg again. Borland Delphi was the first language I used at work in USA. Company was shy about the fact it was using it and advertised position as Visual Basic one. In 1996 Delphi v1 was way better language than Visual Basic, more convenient than Microsoft C.

  2. Yakov has written a very good and succinct article here explaining the logic of why TypeScript is the better way to go for when you need JavaScript in your app or webpage.

  3. Pingback: TypeScript enums

Leave a comment