Understand what TypeScript is
Explore the ways TypeScript makes code more maintainable
Learn how to get the TypeScript compiler
Create our first application in TypeScript
On top of this, TypeScript introduces the idea of public and private members. If an object or function attempts to access a private member of another object the compiler will recognize that the code is invalid and a build error will be generated. This helps implement encapsulation, which is meant to prevent consumers of your TypeScript objects from accessing methods and properties that could be potentially harmful when manipulated outside of the scope of the object itself. Providing accessibility levels helps us limit the scope of possible interactions with an object or even hide it completely from access by other components or libraries.
Writing unit tests has become common practice in software development. Unit tests allow us as developers to refactor and clean code with the safety of knowing that we are not breaking existing functionality. The design decision to include interfaces in the language specification for TypeScript has helped to improve the testability of our code. Writing unit tests help us to verify that small segmented blocks of code always operate as expected. However, as our applications grow we must pass around more complex objects and create more complex functions. This makes testing small segments of code individually more difficult. With the addition of interfaces, it is now easier to mock up objects to be passed around and more tightly control the scope of the tests.
To start writing code in TypeScript, we first need to install the compiler. The compiler is available as a standalone package through Node.js, Visual Studio tooling that Microsoft provides, or you can directly download the compiler's source code. Throughout this text we will be using Visual Studio 2013 as our interactive development environment (IDE). Visual Studio 2013 provides native support for TypeScript with the release of Update 2. For Visual Studio 2012, Microsoft provides an extension that can be installed from the TypeScript home page (http://www.typescriptlang.org/). As TypeScript is becoming more widespread, the number of code editors that have support for it has grown including Eclipse (http://www.jetbrains.com/webstorm/) and Notepad++ (https://github.com/hansrwindhoff/nppPluginTypescript).
As you can see the list of options is fairly extensive so far and will undoubtedly become richer as the language develops. TypeScript 1.0, which will be the version of the language used in this text, provides parameters for everything from specifying the output file to warnings based on code rules. We will discuss all of these options later on, but for now all you need to know is that you can compile your TypeScript code by passing the compiler the path of the file you want to compile. When we begin to build more complicated applications the Visual Studio integrations will provide an easy way for you to set compiler options for all TypeScript files included in your projects.
Now that we have the compiler installed, let's start writing some code. This wouldn't be a good technical book without the inclusion of "Hello World" to get you started with writing code in a new language. The code for this particular example is pretty simple, but we can use it to demonstrate some of the early benefits of switching to TypeScript.
HelloWorld.ts. The following code creates a new HTML paragraph element and sets the text to the value of a pair strings concatenated together:
var p = document.createElement('p'); var hello: string = "Hello"; var world: string = 2; p.textContent = hello + " " + world; document.body.appendChild(p);
world variables, you will see something new. After the variable names, you will see that they are now given the type of
string. This type annotation tells the compiler to always treat the variables
world as strings; however, in this case, the compiler can infer these types from their initial values. Every other reference to these variables will be able to assume that all of the properties and methods of an object of the type
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
This generates the following output:
As you can see, the compiler recognizes that we typed the
world variable as
world to be
string. So let's go back to the TypeScript file and modify the value we are assigning to
world and run the compiler again:
var world: string = "World!";
var p = document.createElement('p'); var hello = "Hello"; var world = "World!"; p.textContent = hello + " " + world; document.body.appendChild(p);
<html> <head> <title>Hello World</title> </head> <body> <script src="HelloWorld.js" ></script> </body> </html>
In general, script tags should be included within the
<head> tag, not in the main
<body> tag. In this case, our code is dependent upon the DOM being ready for our code to execute successfully.
Opening the HTML file in a browser will result in the immediate execution of our code when the document's body loads. As you can see in the following screenshot, our paragraph was added to the HTML on the page and Hello World! is displayed:
To create a new project that includes TypeScript, go to the File menu and navigate to New | Project. In the New Project window, you will see a list of installed templates. There is now a new section named TypeScript; select this section and you will see all of the available project templates that can be used to create TypeScript applications.
The location of this template may vary depending on the version of Visual Studio installed. If the TypeScript section is not available, use the search function of the project template selector.
This does not mean that TypeScript can only be added to these project types—you can add TypeScript files to any existing project. For our examples, we will be using the HTML Application with TypeScript project template, so let's select that and create our new application:
Once the project has been created you will notice a few things right away. First, a default TypeScript file and HTML file have been created to host our new application. There is also a
Now that our project has been created we need to move our code in. Copy the code from
app.ts and do the same with the HTML that was generated. Change the script tag's source attribute to
app.js to reference the new location of our code and run the application. The output displayed should be the same.
Visual Studio has provided a seamless integration with TypeScript and provides a large variety of configuration options. Let's take a look at the project build options first and get a feel for the different things that TypeScript can generate when it is being compiled. To find the build options, right-click on the project in the solution explorer and select Properties from the context menu. As you can see in the following screenshot, we are able to manipulate a large number of the compiler options we saw earlier:
You also have the option for compiling TypeScript files when you save changes to them. This is a helpful option because when a TypeScript file is compiled so are all other TypeScript files that it references. This is a helpful feature when you have only a few files being referenced, but as your applications grow and the dependency trees become more complex you could run into performance issues. Allowing implicit "any" types tells the compiler not to fail if an object's type is not given or cannot be implied. Unchecking this option is the easiest way to force yourself to fully embrace the type system. Although you may run across some scenarios where an "any" type is inevitable they should be very rare. This can be done by providing a type annotation as shown here:
var explicitAny: any;