WHAT IS TYPESCRIPT?

The TypeScript programming language is a free and open source programming language based upon JavaScript. As a matter of fact, any valid JavaScript code is also valid TypeScript code. Therefore What is TypeScript,   TypeScript is a form of JavaScript, but with new features added to it. When you compile the TypeScript code, it actually creates a .js (JavaScript) file for you to use in your web application. In other words, any TypeScript code can be converted to a pure JavaScript equivalent. You may be wondering “if they both can achieve the same results, why should I use TypeScript instead of plain JavaScript?”

In many cases, it actually doesn’t make sense to use TypeScript. This is particularly true if you’re only using JavaScript sparingly to achieve specific tasks. However, in larger applications that contain large amounts of JavaScript code, TypeScript can make it much easier to read/maintain the source code. Although it’s true that JavaScript already supports Object Oriented Programming (OOP), it isn’t as OOP friendly as languages such as C# or Java. JavaScript is also a loosely typed language. This makes it more flexible but also provides more opportunities for mistakes. A loosely typed language (also known as a weakly typed language), is a language which doesn’t require you to declare the type of a variable or object when you create it. Technically, TypeScript can be loosely typed as well, since it doesn’t strictly require you to declare the types of your variables. However, unlike JavaScript, you can also use a strongly typed approach with TypeScript by declaring the types of your variables and objects (hence the name TypeScript).

As mentioned previously, there are many cases when you don’t need the sorts of features offered by TypeScript. However, strong typing can be tremendously helpful in some situations, especially when using an Object Oriented Programming approach. There are also other features of TypeScript (such as interfaces) that are very helpful. Finally, the syntax for creating classes and interfaces is similar to other OOP languages (such as Java or C#), so learning TypeScript is very intuitive if you already have experience with OOP languages.

INSTALLING TYPESCRIPT

TypeScript actually comes pre-installed with Visual Studio 2015. You can download/install the Visual Studio 2015 Com¬munity Edition for free. There are also ways to just install the TypeScript compiler (without installing Visual Studio) and use it with software such as SublimeText or Vim. A common way to use this is by using npm. Feel free to check out how to do it, if you’re curious. I installed Visual Studio 2015, since I wanted to check out the new version of Visual Studio anyway. Installing Visual Studio 2015 is extremely user-friendly. Just visit the following URL and click the “Free Download” button under “Visual Studio Community” (if this doesn’t make sense, then that means Microsoft may have altered the design of their download page, but it should still be easy to figure out regardless):

https://www.visualstudio.com/downloads/

At this point, we still need to properly set our PATH environment variables so that we can use TypeScript from the com¬mand line. Exactly how to add an environment variable to your PATH depends on your operating system. Therefore, I’m not going to waste too much space going into detail about it. A quick Google (or other search engine) search should pro¬vide you with the instructions for your particular operating system. In my case, I used my Windows machine for the project (I figured it will probably be more Microsoft friendly than Linux or Mac), and the value that I needed to add to my PATH is:

C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.8

However, the directory that your TypeScript is installed in might not be the same as mine. Find the directory that the Type¬Script compiler (on Windows, this is tsc.exe) resides in and add that directory to your PATH.

TYPESCRIPT HELLO WORLD

Let’s get started by creating a simple Hello World application. Our first TypeScript program will actually be regular JavaScript code, just to show off how we can also use regular JavaScript in a TypeScript program. We will then start looking at various features that are unique to TypeScript and learn how to use those in our applications. If you’re using Visual Studio 2015, go to File > New > File (starting from the menu at the top of the window). Then, select “Script” in the menu on the left, choose TypeScript file in the center menu, and then click the Open button, as in Figure 3-1. If you’re using a regular text editor, just create a new file and save it as HelloWorld.ts

typescript programming language

Figure 3-1 picture

Add the code shown in Code Listing 3-1 to the file (which we will save as HelloWorld.ts).

Code Listing 3-1: HelloWorld.ts

You may notice that we’re setting the inner HTML of a div named “output” to the output of our helloWorld function. Therefore, we need to create an HTML page with a div named output, and this page will need to reference our script. However, before we do that, let’s compile our TypeScript code (which simply creates an equivalent JavaScript file with the same name). Go to whichever directory you created your TypeScript file in, and then execute the command tsc HelloWorld.ts as shown in Figure 3-2.

What is TypeScript

Figure 3-2

If you look in the current directory (you can do this from the Windows command line with the dir command; if using Linux or Mac you can use the ls command), then you will see that we also have a file named HelloWorld.js within our directory. This JavaScript file was created by the TypeScript compiler, which translates all of our TypeScript into equivalent JavaScript code. We just used standard JavaScript code this time, so if you look at HelloWorld.js, the code is exactly the same as our HelloWorld.ts file. In the next section, we will begin using features unique to TypeScript. Let’s create an HTML file named HelloWorld.html and add the code shown in Code Listing 3-2.

Code Listing 3-2: HelloWorld.html

When you render HelloWorld.html in a browser, it should display “Hello World!”, as in Figure 3-3.

What is TypeScript

Figure 3-3

TYPESCRIPT STATIC TYPING

As I mentioned in the introduction, JavaScript is a loosely typed language which can make it easy to introduce bugs into our code. For example, let’s say we create a function that takes two numbers as arguments and computes their sum:

The correct usage of this sum function would be something like sum(5, 3) which would return 8. How¬ever, what if somebody passed “Five” and “Three” as a and b? This would technically still work, but it would return “FiveThree”, not “Eight”. Likewise, the strings “5” and “3” would return “53” rather than 8, since they won’t get processed as numbers (they would be pro¬cessed as strings, which would result in concatenation rather than addition). This would be an easy mistake to make, and could cause strange behavior within your application once it tries to use these values for other things that expect integers. There are an infinite number of other examples I could come up with that show why the loosely typed nature of JavaScript can be dangerous at times (even though it does add a de¬gree of flexibility). If you’ve spent time writing JavaS¬cript code, then you know what I’m talking about.

In TypeScript, we can identify the types of our vari¬ables when we create them. TypeScript allows us to utilize static typing, which means that all of the variable types are checked at compile time. This is in contrast to dynamic typing, which generally uses the value of a variable to determine its type. We specify the variable/object type by adding a colon and then the type that will be used for the variable. For ex¬ample, to say that variable a is a number, we declare it by writing “a : number”. The above sum function could be re-written in TypeScript so that it warns us if we don’t pass actual numbers as arguments to the function. Create a file named StaticTyping.ts and StaticTyping.html, then add the code shown in Code Listing 4-1 and Code Listing 4-2 to each.

Code Listing 4-1: StaticTyping.ts

Code Listing 4-2: StaticTyping.html

By the way – you may have noticed that we didn’t use a particular div for our output this time, but instead just added it to the body of our document. This is fine for simple examples, but this isn’t generally a sound programming practice. When you try to compile StaticTyping. js, we will receive an error explaining that we’re trying to pass a string as a number, as shown in Figure 4-1.

What is TypeScript

Figure 4-1

However, even though we did receive an error, the TypeScript compiler still creates a StaticTyping.js file. In other words, TypeScript errors are generally more like warnings, since they don’t necessarily prevent our code from compiling into JavaScript. You can see that it still created a JavaScript file named StaticTyping.js (with the JavaScript code that was created from our TypeScript). If you load StaticTyping.html in a browser, you will see that it displays FiveThree as shown in Figure 4-2.

What is TypeScript

Figure 4-2

Technically, we don’t need to obey the typing rules of TypeScript when we create our JavaScript applica¬tions. This may seem like a disadvantage, but TypeScript does at least warn us when we break the rules (unlike JavaScript, which often forces us to figure out things the hard way). If we change the values passed to our sum function from “Five” and “Three” to 5 and 3, you would expect StaticTyping.js to compile without errors. Unfortunately, we just receive another slightly different error, as shown in Figure 4-3.

What is TypeScript

Figure 4-3

Previously, we received an error for trying to assign a string to a number variable. This time, the opposite is true, we are receiving an error for trying to assign a number to a string. If you are using Visual Studio, you can see the red squiggly lines below where our error is being caused, and hovering over that code will display information about the error as shown in Figure 4-4.

What is TypeScript

Figure 4-4

This error is being caused because the innerHTML property expects a string value. This is an easy error to fix. All we need to do is call the toString function on our sum. The correct solution (which won’t result in any errors when you compile) is shown in Code Listing 4-3. You will also notice that I added : number to the end of the signature for our sum function. This basically says “our sum function returns a number”. Once you update the code, compile StaticTyping.ts, and refresh StaticTyping.html, the output should show 8 as in Figure 4-5.

Code Listing 4-3: StaticTyping.ts

 

What is TypeScript

Figure 4-5

TYPESCRIPT CLASSES

If you come from an Object Oriented Programming background, then you will probably prefer the TypeScript syntax for creating classes as opposed to the JavaScript way of creating classes. If you don’t have any familiarity with OOP, then the next example may be a bit confusing. A class is a definition for an object (I like to think of it as a blueprint), primarily in terms of its properties and behaviors. Let’s create a class named BaseballPlayer in a file named BaseballPlayer.ts, as shown in Code Listing 5-1.

In addition to defining our class, we also create a BaseballPlayer object named John Doe, set his various stats, and then display them using the playerStats method. We also only include one constructor, which requires a name, age, and team name to create the BaseballPlayer object. In our next example, we’ll use access modifiers (public, private, protected) and getters/setters. For the sake of simplicity, we left out access modifiers and are just directly setting the other values using regular assignment statements.

Code Listing 5-1: BaseballPlayer.ts

Everything so far should be fairly straightforward – we define a BaseballPlayer object with several different properties (name, age, team, batting average, home runs, and RBIs). We also require three of those properties (name, age, team) when creating an object, since our constructor requires it. A constructor is a function that gets called when an object is created. We also define a method named playerStats which returns a string description of the player and their statistics.

Now, let’s compile BaseballPlayer.ts and then take a look at the code generated in BaseballPlayer.js, which is shown in Code Listing 5-2.

Code Listing 5-2: BaseballPlayer.js

We can now finally see a big difference between our TypeScript code and our JavaScript code. I personally find the structure and syntax of our TypeScript code to be more clear (and elegant) than the equivalent code in JavaScript. Not only does this help when initially writing code, but it also helps when reading and maintaining existing code. This is especially true of large projects, and is probably why Angular 2 is based upon TypeScript. You may disagree, and if you prefer the regular JavaScript way of doing things (which may make sense, if it’s your primary language) then that’s fine – use whatever works best for you.

That’s enough commentary – let’s create an HTML page to see our BaseballPlayer class in action. I named my page Classes.html, but you can name it whatever you want.

Code Listing 5-3: Classes.html

When viewed in a browser, the page should look like Figure 5-1.

What is TypeScript

Figure 5-1

By looking at the output in Classes.html and changing different values in BaseballPlayer.ts, you can clearly see how everything works. If you’re already familiar with Object Oriented Programming, then this example should be clear to you. However, if it is not, then play with the code to figure it out. Don’t forget to re-compile your TypeScript if you change something, because otherwise the JavaScript file won’t change either!

TYPESCRIPT INTERFACES

Finally, we should cover how to create and use an interface in TypeScript. An interface is similar to a class, but it defines an abstract concept rather than an actual object that can be created. For example, an interface for a car radio could include properties that reflect the current volume and station. It could also include behaviors, such as turning the volume up/down and changing the radio station. However, an interface doesn’t include any definitions for the behaviors. An interface doesn’t specify exactly how everything should do what it does – it creates a general design for a class, but allows you to implement that design in any way that fits within the structure of that interface. All of the advantages to using an interface (such as polymorphism) and why you might use an interface instead of a parent class is outside the scope of this article. If you want to thoroughly understand the subject, you’ll need to gain experience in Object Oriented Programming. The surface level view that I just presented, should be enough for you to proceed with the following example.

Let’s say we included players from different types of sports in our program. In our next example, we will include both a BaseballPlayer and BasketballPlayer class. Of course, some things will be similar among these two classes (as well as players of most sports, in general), while other things will be specific only to that particular sport. The things which are universal among players of all sports are appropriate for the Player interface, and the things which are specific to each sport should only exist within each particular class definition. Keep in mind that any behaviors (methods) that may exist between all classes should be included within the interface, even if they are implemented differently between classes. We don’t define the methods within the interface, we simply specify that the class needs to create a definition for that particular method.

Before creating this new TypeScript file, you might want to remove your existing BaseballPlayer.ts and BaseballPlayer. js files, if you’re using Visual Basic. Otherwise, Visual Basic could complain that you have two classes with the same name, although I simply renamed the original class to BaseballPlayer1 to make this annoying message go away. Once you take care of that, create a new file named Interfaces.ts and add the code shown in Code Listing 6-1.

Code Listing 6-1: Interfaces.ts

The properties that will be shared among players of all sports are name, age, and team. Therefore, they all got put into the Player interface. Technically, some sports (such as golf) aren’t team sports, but in those cases, we could just set the team name to the name of the player. We also specify that all classes which implement the Player interface need to have a playerStats method (which as we have seen earlier, is used to display information about the player). We specify that we’re implementing an interface by using the implements keyword followed by the name of the interface, like so:

Once we do this, we will receive errors when compiling our TypeScript, if BasketballPlayer doesn’t properly implement the Player interface. For example, if you remove the name property or the playerStats method from BasketballPlayer, then you will receive a compile time error. As mentioned previously, a JavaScript file will generally still be created, even if there are compile time errors.

Another thing that you may notice is the use of the public and private keywords. These are known as access modifiers which are used to grant/restrict access to members (by members I mean fields/ properties and methods). The public access modifier declares that any class may access that member. The private access modifier declares that a particular member may only be accessed within the class itself. There are other access modifiers such as protected (which only allows a class and its subclasses access) and readonly (which allows only read only access). However, we’re only using private and public in our example program.

The name, age, and team of our classes are public. We actually can’t make members of a class that are from an interface private, which is why you should only include something in an interface if you want it to be available to any class. Since the name, age, and team are all part of the Player interface, we can’t make them private in our classes. However, we do make the statistics of our players private. If we tried to access them directly outside the class, like in the original BaseballPlayer.ts shown in Code Listing 5-1 (for example, johnDoe.battingAverage = 0.326), we would receive an error. Instead, we need to use the setBattingAverage method to modify the batting average, like below:

Using the private access modifier so that you can’t directly modify the data, and then supplying getter/setter methods is a common pattern in the programming world. In this particular case, they don’t really make much of a difference. However, in the real world, you can use conditional logic within your setter methods to ensure that the fields are being set properly, rather than being set to any value the user wants. Furthermore, you could only provide a getter method (with no setter). so that the field is essentially read-only outside of the class. With that being said, getter/setter methods are often used in cases when they aren’t really necessary. However, I still wanted to present them. Although I created getters/setters in the traditional way, you can also use the get and set keywords within TypeScript instead of getters/setters. The get/set keywords in TypeScript work the same as C#, so if you have experience with that language you shouldn’t have any trouble putting them to use. Otherwise, you may want to read the TypeScript documentation prior to using them.

Let’s compile Interfaces.ts (which will generate Interfaces.js), and create an HTML file that loads our Interfaces.js file using the code in Code Listing 6-2.

Code Listing 6-2: Interfaces.html

When you open Interfaces.html in a browser, it should render similar to Figure 6-1.

What is TypeScript

Figure 6-1

That is as far as we’re going to go in this article, but there are plenty of other features within TypeScript. Some of the features we haven’t covered include abstract classes (which are similar to interfaces), generics, compiler options (specified using JSON in tsconfig.json), enumerators and modules, to name a few. Through writing this article, I learned quite a bit about TypeScript and will often use it whenever I do Object Oriented Programming with JavaScript. It might not make JavaScript perfect, but there are some major improvements upon it that TypeScript offers to developers for free.

 

Leave a Reply

Your email address will not be published. Required fields are marked *