SYS-CON MEDIA Authors: Pat Romanski, Gary Arora, Zakia Bouachraoui, Yeshim Deniz, Liz McMillan

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

Latest Stories
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
On-premise or off, you have powerful tools available to maximize the value of your infrastructure and you demand more visibility and operational control. Fortunately, data center management tools keep a vigil on memory contestation, power, thermal consumption, server health, and utilization, allowing better control no matter your cloud's shape. In this session, learn how Intel software tools enable real-time monitoring and precise management to lower operational costs and optimize infrastructure...
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical Infrastructure as a Service cloud provider but it's been designed around data privacy," explained Julian Box, CEO and co-founder of Calligo, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Isomorphic Software is the global leader in high-end, web-based business applications. We develop, market, and support the SmartClient & Smart GWT HTML5/Ajax platform, combining the productivity and performance of traditional desktop software with the simplicity and reach of the open web. With staff in 10 timezones, Isomorphic provides a global network of services related to our technology, with offerings ranging from turnkey application development to SLA-backed enterprise support. Leadin...
While a hybrid cloud can ease that transition, designing and deploy that hybrid cloud still offers challenges for organizations concerned about lack of available cloud skillsets within their organization. Managed service providers offer a unique opportunity to fill those gaps and get organizations of all sizes on a hybrid cloud that meets their comfort level, while delivering enhanced benefits for cost, efficiency, agility, mobility, and elasticity.
DevOps has long focused on reinventing the SDLC (e.g. with CI/CD, ARA, pipeline automation etc.), while reinvention of IT Ops has lagged. However, new approaches like Site Reliability Engineering, Observability, Containerization, Operations Analytics, and ML/AI are driving a resurgence of IT Ops. In this session our expert panel will focus on how these new ideas are [putting the Ops back in DevOps orbringing modern IT Ops to DevOps].
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Enterprises are striving to become digital businesses for differentiated innovation and customer-centricity. Traditionally, they focused on digitizing processes and paper workflow. To be a disruptor and compete against new players, they need to gain insight into business data and innovate at scale. Cloud and cognitive technologies can help them leverage hidden data in SAP/ERP systems to fuel their businesses to accelerate digital transformation success.
Most organizations are awash today in data and IT systems, yet they're still struggling mightily to use these invaluable assets to meet the rising demand for new digital solutions and customer experiences that drive innovation and growth. What's lacking are potent and effective ways to rapidly combine together on-premises IT and the numerous commercial clouds that the average organization has in place today into effective new business solutions.
Concerns about security, downtime and latency, budgets, and general unfamiliarity with cloud technologies continue to create hesitation for many organizations that truly need to be developing a cloud strategy. Hybrid cloud solutions are helping to elevate those concerns by enabling the combination or orchestration of two or more platforms, including on-premise infrastructure, private clouds and/or third-party, public cloud services. This gives organizations more comfort to begin their digital tr...
Keeping an application running at scale can be a daunting task. When do you need to add more capacity? Larger databases? Additional servers? These questions get harder as the complexity of your application grows. Microservice based architectures and cloud-based dynamic infrastructures are technologies that help you keep your application running with high availability, even during times of extreme scaling. But real cloud success, at scale, requires much more than a basic lift-and-shift migrati...
David Friend is the co-founder and CEO of Wasabi, the hot cloud storage company that delivers fast, low-cost, and reliable cloud storage. Prior to Wasabi, David co-founded Carbonite, one of the world's leading cloud backup companies. A successful tech entrepreneur for more than 30 years, David got his start at ARP Instruments, a manufacturer of synthesizers for rock bands, where he worked with leading musicians of the day like Stevie Wonder, Pete Townsend of The Who, and Led Zeppelin. David has ...
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Addteq is a leader in providing business solutions to Enterprise clients. Addteq has been in the business for more than 10 years. Through the use of DevOps automation, Addteq strives on creating innovative solutions to solve business processes. Clients depend on Addteq to modernize the software delivery process by providing Atlassian solutions, create custom add-ons, conduct training, offer hosting, perform DevOps services, and provide overall support services.