TypeScript Language Primer

typescript-language-primer

What is TypeScript?

TypeScript is an open source typed superset of JavaScript which compiles to plain JavaScript. Many people have considered JavaScript’s loose typing as a problem, but now TypeScript offers a solution to that. Specifically, TypeScript allows you to code with decorators/annotations, classes, interfaces, private properties and typing compliance.

We also might say that TypeScript is ES6 with some extra options.

What does TypeScript do?

TypeScript formalizes JavaScript’s types compiling and even offers auto-completion with some IDEs, which of course makes our lives as developers easier. If you do not place much value on auto-completion, TypeScript also provides other features which may interest you, for example syntax validation and types checking. There is now a real trend in the evolution of web applications toward the development of Large SPAs (Single Page Applications). In this context, JS is being pushed hard and TS is one of the tools that has been developed to enable strict typing validation during compilation, thereby keeping consistency within your code. TS detects some syntax errors that would normally only be found during testing, such as a function that is ready to handle an integer parameter and eventually is called with one of type string. It is worth noting that TypeScripts’s syntax is very similar to Java, Csharp and C++ rather than ruby or python.

Developers typically install TypeScript using the npm (node package manager). When doing this you need to create a tsconfig.json file which will allow you to define the JavaScript target, module type, module resolution type and so on. Some options that I consider important are: watch, noImplicitAny and removeComments; set them respectively as true, false, false.

Watch keeps observing your TS files and automatically compiles when there is any change; setting the noImplicitAny flag to false means that the compiler will not supply an error if you do not explicitly type variables  rather it just assumes they have type ‘any’; removeComments will help you to map the differences between TS code and JS. Though, comments might be removed after processing JS files in minification.

What are the differences between TypeScript and plain JavaScript?

In my opinion the key points worth highlighting about TS are (note: items with 1.8 is only available from it):

  1. Learning TS does not require learning a new language, actually, it is being aligned to the new EcmaScript 2015 language specification;
  2. Interface: developers can define their types as interfaces and add them to parameters and returns for methods and functions thereby increasing the readability of the code;

    1. Inheritance;

      • interfaces can be implemented by classes;

      • classes can extend other classes;

    1. Arrow function: it is way helpful as resolving context for “this” in event handlers;

    1. Typing is optional: it means that if you do not define a type for a variable, it will behave as an idiomatic JavaScript (the type by default is “any”);

    1. Destructuring;

Being able to decompose an object/array into variables is very helpful to get develop clean code: think more, code less.

      • Destructuring object;

      • Destructuring array;

    1. Declaring private properties (Although technically they are not a private property);

Although you can declare a property as private, it does not work as a private property at runtime. As I already said, TS is just a superset of JS which runs and validates the code at compilation time. So, be careful! It is really important to know what the compiler does with your code.

    1. Control flow analysis errors (1.8);

The TS compilation process is able to be customized enabling even more strict validation as you can see below.

      1. Unreachable code (off by default, enable through –allowUnreachableCode);
      2. Unused labels (off by default, enable through –noImplicitReturns);
      3. Implicit returns (off by default, enable through –noFallthroughCasesInSwitch);
    1. Simplified props type management in React;

You might use destructuring and defaults to define props easily. See the following code:

    1. Augmenting global/module scope from modules;

We can create not only classes, but also compositions.For example, let’s say that you’re using a type but need to add some extra methods…

    1. String literal types validation (1.8)

String literal validation is more like enums. It is easy to understand that you can define possible values for a property as shown in the code below.

    1. Let/const in loops are correctly captured (1.8)

Previously, variables declared within loop statements using let or const operator weren’t allowed be accessed inside closures.

    1. Modules are now emitted with the “use strict”; prologue (1.8)

All modules are parsed in strict mode. Previously, they were compiled with strict mode just for ES6 target. This implies that the code used to silently fail at runtime, such as assigning to NaN. In TS code this will now loudly fail.

  1. Custom JSX factories using –reactNamespace

During the compilation you can specify the factory using the parameter “—reactNamespace <your factory name here>”. Knowing so, we can run some examples.

There are many other features beyond the ones that I have discussed in this post. This subset has function and code style guide at a high level. As you can see TS has many features that ensure consistency and quality of code.

Should I be careful with TypeScript?

There are some aspects of TS which you need to consider:

  • Be careful with the extra features, otherwise you will end up depending on the TS;
  • There is no annotation/decorator for ES 2015: it requires a polyfill to keep consistent;
  • Private properties are assigned to object context “this”, it means that is not private at all. Everybody knows that once you have functions or values assigned to the object context “this”, it becomes public. But the superset validation is performed at compile time, then, if you try to access a “private” property, it will be considered a violation and it won’t compile your TS code;
  • Keep in mind that TypeScript is an extension to JavaScript to force variable typing, but what makes JS powerful is that it is a dynamically typed language and so you need to be careful to not overuse TypeScript.
  • So, in which cases is loose typing important? JavaScript does not have polymorphism.

Think about providing a promise for a map based on an array of elements and that you could also receive a promise as input.

Well, knowing that we do not have polymorphism and getMap has to provide the same result for both cases, you can see that loose typing is very powerful if used when required.

 

Should I use TypeScript?

The answer is pretty simple. As with any other language, you need to understand your product’s domain and then find the language which suits it best. If you are thinking about starting a new web project you will most likely end up using JavaScript and so I would recommend using Babel as this will provide future proofing if you wish to remove the compiler when browsers are capable of natively interpreting ES2015.  In the meantime you can get some of these advantages today by using TypeScript rather than using simple ES2015.

References

Anders Hejlsberg: Introducing TypeScript

https://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript

Why TypeScript is Hot Now, and Looking Forward

http://blog.teamtreehouse.com/typescript-hot-now-looking-forward

The rise of TypeScript?

http://developer.telerik.com/featured/the-rise-of-typescript

Github (Microsoft/TypeScript)

https://github.com/Microsoft/TypeScript/wiki/What’s-new-in-TypeScript

Why TypeScript isn’t the answer

http://walkercoderanger.com/blog/2014/02/typescript-isnt-the-answer


Ready to start collect logs from your Javascript applications? Create a free Logentries account in less than a minute at logentries.com.

Tagged with: , , , , , , ,
Posted in JavaScript

Leave a Reply