From the Trenches of the Enterprise Software

Yakov Fain

Subscribe to Yakov Fain: eMailAlertsEmail Alerts
Get Yakov Fain: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Blog Feed Post

Why program in TypeScript

TypeScript is a compile-to-JavaScript language, which was released by Microsoft as an open source project in 2012. It’s 2018 now, and neither Web browsers nor server-side JavaScript engines support TypeScript.

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 a 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, which means that you can take any JavaScript file, e.g. myProgram.js, change its name extension from .js to .ts, and the file myProgram.ts becomes a valid TypeScript program without changing a single line of code.

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.

https://yakovfain.files.wordpress.com/2018/09/u0_playground.png?w=1517&h... 1517w, https://yakovfain.files.wordpress.com/2018/09/u0_playground.png?w=150&h=41 150w, https://yakovfain.files.wordpress.com/2018/09/u0_playground.png?w=300&h=81 300w, https://yakovfain.files.wordpress.com/2018/09/u0_playground.png?w=768&h=209 768w, https://yakovfain.files.wordpress.com/2018/09/u0_playground.png?w=1024&h... 1024w" sizes="(max-width: 760px) 100vw, 760px" />

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 into 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. For current statistics, visit this page.

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

5. According to the StackOverflow Survey 2018, TypeScript is the fourth most loved language.
***************

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

Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain