TypeScript Vs JavaScript

TypeScript Vs JavaScript

Last updated on 25th Sep 2020, Artciles, Blog

About author

Pranav (Sr Technical Project Manager - Java )

He is a TOP-Rated Domain Expert with 6+ Years Of Experience, Also He is a Respective Technical Recruiter for Past 3 Years & Share's this Informative Articles For Freshers

(5.0) | 15497 Ratings 533

If you have ever worked on a web development project, you must have seen what JavaScript is like. JavaScript has been there for a long time now as the most popular scripting language for many web projects.

Typescript is an open-source programming language most suited for large applications. It was developed by Microsoft in 2012, mainly because JavaScript code was becoming too complex to handle when it comes to large-scale applications.

Difference between Typescript and Javascript

Essentially, all your JavaScript code is also valid in Typescript – that means Typescript is a superset of JavaScript – or

  • JavaScript + more features = Typescript.

So, if you save your JavaScript (.js) file with a Typescript (.ts) extension, it will work perfectly fine. But that does not mean that Typescript and JavaScript are the same.

Before outlining the differences between both, let us understand what each language looks like!

Subscribe For Free Demo

Error: Contact form not found.

JavaScript

JavaScript is one of the most popular core technologies of the web. From the beginning, it has been an integral part of web applications making web pages interactive and dynamic. It is a high-level language, with JIT (Just-in-Time) compiler and dynamic typing. For long, JS was a client-side implementation, but some newer JS engines also have server-side implementations. The syntax of JS is very similar to Java, and so are the standard libraries. As a starting point, JS is the best scripting language to learn.

JavaScript was developed by Netscape in collaboration with Sun Microsystems.

Some unique features of JavaScript are –

  • Flexible, dynamic and cross-platform
  • used for both client-side and server-side
  • Lightweight interpreted
  • Supported by all browsers
  • Weakly typed
  • JIT compilation

Let us take a simple example to illustrate how JavaScript works. The following simple HTML code is to validate a username field where myFunction() is written in JavaScript.

If you observe, the syntax of the functions is similar to Java, however, we have defined the variables as ‘var’ and not declared them as any type. The myFunction() function is triggered when the user clicks on a ‘Submit’ button and gives appropriate alert messages as per the conditions. Here is sample output –

It is that simple! If you know Java, JavaScript is fairly simple to learn.

TypeScript

TypeScript is no different from JavaScript in its purpose but is used for developing large applications. TypeScript trans compiles (source to source compilation) to JavaScript. It follows an object-oriented programming language structure and supports its features like classes, interfaces, namespaces, and inheritance. Static typing is possible in TypeScript through type annotations (numbers, string and boolean). For example,

  • class Student {
  • private name: string;
  • }

As we see above, TypeScript is strongly typed. This makes it better to debug (during compile time itself) which is a more efficient way to code for large projects. TypeScript programs typically consist of modules, functions, variables, comments, expressions, and statements – just like any other full-fledged programming language. Some prominent features of TypeScript are –

  • Easy to maintain and enhances project productivity
  • Static typing and annotations are possible
  • Supports object-oriented features like interface, inheritance, and classes
  • Easy to debug and early detection of errors
  • Supports ES6 (ECMAScript) that offers easier syntax to handle objects and inheritance features
  • The good full-fledged IDE support

Does that make TypeScript better than JavaScript?

Before further comparison of TypeScript and JavaScript, another important question needs to be addressed! Since TypeScript is a superset of JavaScript, should we always use Typescript? Does being a superset make TypeScript suitable for all types of projects?

No.

TypeScript is no way to replace or make JavaScript obsolete. JavaScript is still the most favorite client-side scripting language. For smaller projects, using TypeScript could be an overhead because it takes time to trans compile the code into JavaScript, which is an extra step.

JavaScript is directly run on the browser, so for small code chunks, it’s easier to refresh and debug the code. In the case of TypeScript, we need a proper IDE and set up to run the code.

When should you migrate your project to TypeScript?

When the code becomes huge, complex to handle, and more prone to errors, it is better if some errors are caught during compile time itself. That is where TypeScript helps. The beauty is that the entire codebase written in Java can be reused as such.

Typescript vs Javascript: Head to head comparison

Now as we understand the basic features and purpose of both, let us explore some more low-level differences apart from what we have already learned so far –

TYPESCRIPT JAVASCRIPT
Superset of JavaScript developed to overcome code complexity for large projectsA scripting language that helps create dynamic web page content
Errors can be found and corrected during compile timeErrors can be found only during run-time as it is an interpreted language
Strongly typed, supports both static and dynamic typingWeakly typed, no option for static typing
Converted into JavaScript code to be understandable for browsersCan be directly used in browsers
Since it is a superset, all the JavaScript libraries, and other JavaScript code works without any changesJS libraries work by default
There is support for ES3, ES4, ES5 and ES6No support for compiling additional ES3, ES4, ES5 or ES6 features
Supports modules, generics and interfaces to define dataNo support for modules, generics or interface
Functions can have optional parametersThis feature is not possible in JavaScript
An example code –function multiply (a, b) {return a*b;}var result = multiply(a, b);console.log(‘The answer is – ’ + result);Example code –<script>function multiply (a, b) {return a*b;}var result = multiply(a, b);document.write (‘The answer is – ’ + result);</script>
Numbers, Strings are considered as interfaces.Number, string are objects.
Powerful and intuitive languageNeat and clean, most suitable for simple web applications
The community support is still growing and not so hugeHuge community support with lots of documentation and support for solving issues
Prototyping is possiblePrototyping support is not there
Takes time to learn and code, scripting knowledge is a must.Can be learned on the go, no prior scripting experience is needed.
Proper build setup (npm package) is required for static type definitionsNo build setup is required

Why is TypeScript developed while having JavaScript?

When JavaScript was developed then the JavaScript development team introduced JavaScript as a client-side programming language. But when people were using JavaScript then developers got to know that JavaScript can be used as a server-side programming language also. But When JavaScript was growing then the code of JavaScript became complex and heavy. Because of this, JavaScript was even not able to fulfill the requirement of Object-oriented programming language. This prevents JavaScript from succeeding at the enterprise level as a server-side technology. Then TypeScript was developed by the development team to bridge this gap.

Features of TypeScript:

  • TypeScript Code is converted into Plain JavaScript Code:: TypeScript code is not understandable by the browsers. That’s why if the code is written in TypeScript then it is compiled and converted the code i.e. translate the code into JavaScript.The above process is known as Trans-piled. By the help of JavaScript code, browsers are able to read the code and display.
  • JavaScript is TypeScript: Whatever code is written in JavaScript can be converted to TypeScript by changing the extension from .js to .ts.
  • Use TypeScript anywhere: TypeScript code can be run on any browser, devices or in any operating system. TypeScript is not specific to any Virtual-machine etc.
  • TypeScript supports JS libraries: With TypeScript, developers can use existing JavaScript code, incorporate popular JavaScript libraries, and can be called from other JavaScript code.

Difference between TypeScript and JavaScript:

  • TypesScript is known as an Object oriented programming language whereas JavaScript is a scripting language.
  • TypeScript has a feature known as Static typing but JavaScript does not have this feature.
  • TypeScript gives support for modules whereas JavaScript does not support modules.
  • TypeScript has Interface but JavaScript does not have Interface.
  • TypeScript supports optional parameter functions but JavaScript does not support optional parameter functions.

Advantages of using TypeScript over JavaScript

  • TypeScript always points out the compilation errors at the time of development only. Because of this at the run-time the chance of getting errors are very less whereas JavaScript is an interpreted language.
  • TypeScript has a feature which is strongly-typed or supports static typing. That means Static typing allows for checking type correctness at compile time. This is not available in JavaScript.
  • TypeScript is nothing but JavaScript and some additional features i.e. ES6 features. It may not be supported in your target browser but TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 also.

Disadvantages of using TypeScript over JavaScript

  • Generally TypeScript takes time to compile the code.
Course Curriculum

Get JavaScript Training with Advanced Topics From Real-Time Experts

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

Defining TypeScript

TypeScript is an open source syntactic superset of JavaScript that compiles to JavaScript (EcmaScript 3+). TypeScript offers type annotations which provide optional, static type checking at compile time. Since it is a superset of JavaScript, all JavaScript is syntactically valid TypeScript. However, that does not mean all JavaScript can actually be processed by the TypeScript compiler:

  • let a = ‘a’;
  • a = 1; // throws: error TS2322: Type ‘1’ is not assignable to type ‘string’.

Benefits of TypeScript

Type Annotations

TypeScript was created to “statically identify constructs that are likely to be errors”. This allows us to make safe assumptions about state during execution. Let’s compare the following JavaScript and TypeScript functions:

compare the following JavaScript and TypeScript functions:

  • // Basic JavaScript
  • function getPassword(clearTextPassword) {
  • if(clearTextPassword) {
  • return ‘password’;
  • }
  • return ‘********’;
  • }
  • let password = getPassword(‘false’); // “password”

Nothing in JavaScript will prevent a script from calling getPassword(…) with invalid (non-boolean) parameters which will result in a silent error at runtime. This can be entirely avoided at compile time using TypeScript’s type annotations:

  • // Written with TypeScript
  • function getPassword(clearTextPassword: boolean) : string {
  • if(clearTextPassword) {
  • return ‘password’;
  • }
  • return ‘********’;
  • }
  • let password = getPassword(‘false’); // throws: error TS2345: Argument of type ‘”false”‘ is not assignable to parameter of type ‘boolean’.

This contrived example demonstrates how we can prevent operations from acting on objects of an unexpected type. Historically, one of the biggest complaints of JavaScript was the difficulty in tracking down issues because of the lack of type checking combined with things like type coercion which may cause undesired results for those who aren’t familiar with JavaScript intricacies.

Language Features

In addition to static type analysis, TypeScript also adds the following features to JavaScript:

  • Interfaces
  • Generics
  • Namespaces
  • Null checking
  • Access Modifiers

API Documentation

Suppose the above getPassword(…) function belonged to an external library. How would I, as a consumer of that library, know the type to pass into the function? There are jsdoc comments that many IDEs and editors, such as VSCode support. Then there is the library’s own documentation, which tools like Dash make more accessible. But none of these provide the kind of experience offered by TypeScript out of the box.

Consider the fetch API as an example. The following screenshot demonstrates how we can explore the API using the VSCode Peek Definition feature. Using these tools we can quickly discover the input parameter types (RequestInfo = Request | string and RequestInit) and the return type (Promise<Response>). These kinds of tools go well beyond what is available through classic JavaScript and jsdocs.

 classic-JavaScript-and-jsdocs

Misconceptions

There are many misconceptions around why someone might choose TypeScript. I’ve cherry-picked a few to discuss here.

  • ES6 Features: One of the most common reasons for choosing TS is the desire to use ES6 features like modules, classes, arrow functions, and others. However, this is not a good reason for choosing TypeScript since the same thing can be achieved using Babel. In fact, it is not uncommon to see TypeScript and Babel used in the same application.
  • It’s Easier Than JavaScript: For the most part this statement is subjective but there are valid arguments that TS introduces syntax noise. The most important thing however, is that TS does not hide JS. It is not an excuse for disregarding JavaScript fundamentals. TS is still a superset of JavaScript and does not provide protection from many of the common complaints against JavaScript which are unrelated to the lack of static type checking (this, scopes, prototypes, etc.). Because of this, developers should still maintain strong JS competence.
  • Type Correctness == Program Correctness: While this may seem like an obviously incorrect statement, I believe static type checking provides an artificial safety net that developers can take for granted and is worth discussing. If type correctness does not imply program correctness, then what can we do to continually and repeatedly ensure our program does what we intend? The best answer I’m aware of is unit testing. So, it begs the question that if we intend to prove our program is correct through unit tests, these tests should also prevent most type errors.
  • Static Typing Gives You Tree-Shaking: Tree shaking refers to dead-code elimination through the use of static constructs like named module import/export and const. TypeScript does not currently support tree-shaking out of the box.

Syntax and Compilation Comparison

It is common to hear developers choosing TypeScript because of features like modules and classes. However, it is important to understand these features are also available in JavaScript since ES6 and you can use Babel to transpile down to ES5 for greater browser compatibility. Because of this confusion, here is a quick syntax comparison for some of the more recent EcmaScript features. For each feature, you’ll find the TypeScript version and its compiled ES5 JavaScript along with the dynamic ES6 definition transpiled to ES5 using babel.

Course Curriculum

Enroll in JavaScript Certification Course to UPGRADE Your Technical Skills

Weekday / Weekend BatchesSee Batch Details

Classes

  • // — TypeScript — //
  • class Article {
  • name: string;
  • constructor(name: string) {
  • this.name = name;
  • }
  • }
  • // — TypeScript compiled output — //
  • var Article = /** @class */ (function () {
  • function Article(name) {
  • this.name = name;
  • }
  • return Article;
  • }());
  • // — JavaScript with Babel — //
  • class Article {
  • constructor(name) {
  • this.name = name;
  • }
  • }
  • // — Babel compiled output — //
  • “use strict”;
  • function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(“Cannot call a class as a function”); } }
  • var Article = function Article(name) {
  •  _classCallCheck(this, Article);
  • this.name = name;s
  • };

Modules

  • // — TypeScript — //
  • export default class Article { }
  • // — TypeScript compiled output — //
  • define([“require”, “exports”], function (require, exports) {
  • “use strict”;
  • Object.defineProperty(exports, “__esModule”, { value: true });
  • var Article = /** @class */ (function () {
  • function Article() {
  • }
  • return Article;
  • }());
  • exports.default = Article;
  • });
  • // — JavaScript with Babel — //
  • export default class Article { }
  • // — Babel compiled output — //
  • “use strict”;
  • Object.defineProperty(exports, “__esModule”, {
  • value: true
  • });
  • unction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(“Cannot call a class as a function”); } }
  • var Article = function Article() {
  •  _classCallCheck(this, Article);
  • };
  • exports.default = Article;

Optional Parameters

  • // — TypeScript — //
  • function log(message: string = null) { }
  • // — TypeScript compiled output — //
  • function log(message) {
  • if (message === void 0) { message = null; }
  • }
  • // — JavaScript with Babel — //
  • function Log(message = null) { }
  • // — Babel compiled output — //
  • “use strict”;
  • function Log() {
  • var message = arguments.length > 0 && arguments[0] !==undefined ? arguments[0] : null;
  • }

When To Choose: Typescript vs. JavaScript

TypeScript

Prefer Compile Time Type Checking:

It is entirely possible to perform runtime type verification using vanilla JavaScript. However, this introduces additional runtime overhead that could be avoided by performing compile-time validation

Working with a New Library or Framework:

Let’s suppose you’re taking up React for a new project. You are not familiar with React’s APIs, but since they offer type definitions, you can get intellisense that will help you navigate and discover the new interfaces.

Large Projects or Multiple Developers:

TypeScript makes the most sense when working on large projects or you have several developers working together. Using TypeScript’s interfaces and access modifiers can be invaluable in communicating APIs (which members of a class are available for consumption).

JavaScript

Build Tools Required:

TypeScript necessitates a build step to produce the final JavaScript to be executed. However, it is becoming increasingly rare to develop JavaScript applications without build tools of any kind.

Small Projects:

TypeScript may be overkill for small teams or projects with a small code surface area.

Strong Testing Workflow:

If you have a strong JavaScript team who is already implementing test-driven development, switching to TypeScript may not give you enough to make it worth the associated costs.

Added Dependencies:

In order to use libraries with TS, you will need their type definitions. Every type definition means an extra npm package. By depending on these extra packages you are accepting the risk that these may go un-maintained or may be incorrect. If you choose not to import the type definitions, you are going to lose much of the TS benefit. Note that the DefinitelyTyped project exists to mitigate these risks. The more popular a library is, the more likely the type definitions are to be maintained for the foreseeable future.

Framework Unsupported:

If your framework of choice does not support TS, such as EmberJS (although this is planned and is the language of choice for Glimmer), then you may be unable to take advantage of its features.

Javascript Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Other Considerations

So you’ve decided that it’s time to introduce a type system to your front-end development workflow. Is TypeScript the only option? The short answer is no. In fact, there are two other major tools for type annotations which are worth consideration and have been discussed elsewhere.

  • Facebook’s Flow
  • Google’s Closure

If you need to monitor your javascript application so you can have front and back end in place, make sure you use an APM. Stackify Retrace supports javascript and can help you continuously improve your applications. Learn more about Javascript APM, better known as our Real User Monitoring.

Conclusion

As we have already determined, JavaScript is most suited when your team is new and is working on small web projects. If you have a team with good expertise and knowledge and want them to handle a complex project, going for TypeScript is a perfect choice. That said, if you are looking for a learning curve and job opportunities, definitely TypeScript has an edge over JavaScript. TypeScript developers are paid an average salary of $148,000 per year whereas JS developers are typically paid around $110,000 per year. If you learn TypeScript, you can work on both JS as well as TypeScript projects. Start learning TypeScript here.

Are you looking training with Right Jobs?

Contact Us

Popular Courses