7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
Advertisement
  1. Code
  2. Web Development

Getting Started With TypeScript

Scroll to top
Read Time: 12 mins

In late 2012, Microsoft introduced TypeScript, a typed superset for JavaScript that compiles into plain JavaScript. TypeScript is gaining popularity these days because it adds enhanced features to JavaScript and is also used in JavaScript frameworks such as Angular.

TypeScript improves the developer experience, allows for the creation of highly scalable large applications, and allows for easy tracking of bugs during development. It is an open-source language that focuses on implementing object-oriented features, such as classes, type annotations, inheritance, modules, and much more.

In this tutorial, we will get started with TypeScript, using simple bite-sized code examples, compiling them into JavaScript, and viewing the instant results in a browser.


TypeScript Setup

To set up TypeScript for your project, all you need is a text editor, a browser, and the TypeScript package to use TypeScript. Follow these installation instructions:

If you receive a permission error while installing the package on a Mac OS or Linux, you can run this command:

  • To check for the TypeScript version, type this command in the terminal:

That's it—we are now ready to make a simple Hello World application in TypeScript!


Hello World in TypeScript

TypeScript is a superset of ECMAScript 5 (ES5) and incorporates features of ES6. Because of this, any JavaScript program is already a TypeScript program. The TypeScript compiler performs local file transformations on TypeScript programs. Hence, the final JavaScript output closely matches the TypeScript input.

First, let's create a hello-world folder in the text editor, and then we will create a basic index.html file in this folder and reference an external script file:

This is a simple "Hello World" application, so let's create a file named hello.ts. The *.ts extension designates a TypeScript file. Add the following code to hello.ts:

Next, open the command-line interface, navigate to the folder containing hello.ts, and execute the TypeScript compiler with the following command:

The tsc command is the TypeScript compiler, and it immediately generates a new file called hello.js. Our TypeScript application does not use any TypeScript-specific syntax, so we see the same JavaScript code in hello.js that we wrote in hello.ts.

Great! Now we can explore TypeScript's features and see how it can help us maintain and author large-scale JavaScript applications.

hello world in typescript

Configuring the TypeScript Compiler

A .ts file is initially compiled to ES5 by the TypeScript compiler. However, because TypeScript also supports ES6 syntax, which is much newer, we will learn how to configure the TS compiler to target other JavaScript versions like ES6.

In the terminal, run:

This command generates a configuration file called tsconfig.json. This file consists of a lot of settings, one of which is the target. The target specifies the version of the JavaScript file the TS compiler will generate.

Now, open the tsconfig.json file and change the target from es5 to es6 to ensure we have the safest option for all browsers.

Type Annotations

Type annotations are an optional feature, which allows us to check and express our intent in the programs we write. Let's create a simple area() function in a new TypeScript file, called type.ts.

Next, change the script source in index.html to type.js and run the TypeScript compiler with tsc type.ts. Refresh the page in the browser, and you should see the following:

app output

As shown in the previous code, the type annotations are expressed as part of the function parameters; they indicate what types of values you can pass to the function. For example, the shape parameter is designated as a string value, and width and height are numeric values.

Type annotations, and other TypeScript features, are enforced only at compile-time. If you pass any other types of values to these parameters, the compiler will give you a compile-time error. This behavior is extremely helpful while building large-scale applications. For example, let's deliberately pass a string value for the width parameter:

We know this results in an undesirable outcome, and compiling the file alerts us to the problem with the following error:

Notice that despite this error, the compiler generated the type.js file. The error doesn't stop the TypeScript compiler from generating the corresponding JavaScript, but the compiler does warn us of potential issues. We intend width to be a number; passing anything else results in undesired behavior in our code. Other primitive types include bool or even any used when trying to prevent type errors on a particular variable.

Additionally, TypeScript added some extra type annotations to its features.

Tuples

Tuples are fixed-length arrays where each element has a particular type.


Looking at the code above, the array has a fixed length of two elements representing the name of a shape and area; the first element is of type string and the second element is of type number. If we try adding a third element, for example a type number, we'll get an error:

Enum

Enums hold groups of related constant identifiers or values. They are defined using the enum keyword Let's look at the code sample below:

The code above is an example of a string enum type. There is also the numeric enum type, which stores string values as numbers.

Interfaces

Let's expand our example to include an interface that further describes a shape as an object with an optional color property. Create a new file called interface.ts, and modify the script source in index.html to include interface.js. Type the following code into interface.ts:

Interfaces are names given to object types. Not only can we declare an interface, but we can also use it as a type annotation.

Compiling interface.ts results in no errors. To evoke an error, let's append another line of code to interface.ts with a shape that has no name property and view the result in the console of the browser. Append this line to interface.ts:

Now, compile the code with tsc interface.ts. You'll receive an error, but don't worry about that right now. Refresh your browser and look at the console. You'll see something similar to the following screenshot:

app screenshot

Now let's look at the error. It is:

We see this error because the object passed to area() does not conform to the Shape interface; it needs a name property in order to do so.


Arrow Function Expressions

Understanding the scope of the this keyword is challenging, and TypeScript makes it a little easier by supporting arrow function expressions, a feature supported in ECMAScript 6. Arrow functions preserve the value of this, making it much easier to write and use callback functions. Consider the following code:

The this.name on line 7 will clearly be empty, as demonstrated in the browser console:

empty name

We can easily fix this issue by using the TypeScript arrow function. Simply replace function() with () =>.

And the results:

name filled in

Take a peek at the generated JavaScript file. You'll see that the compiler injected a new variable, var _this = this;, and used it in setTimeout()'s callback function to reference the name property.


Classes With Public and Private Accessibility Modifiers

TypeScript supports classes, and their implementation closely follows ECMAScript 6. Let's create another file, called class.ts, and review the class syntax:

The above Shape class has two properties, area and color, one constructor (aptly named constructor()), as well as a shoutout() method. The scope of the constructor arguments (name, width, and height) are local to the constructor. This is why you'll see errors in the browser, as well as the compiler:

errors

Next, let's explore the public and private accessibility modifiers. Public members can be accessed everywhere, whereas private members are only accessible within the scope of the class body. There is, of course, no feature in JavaScript to enforce privacy, hence private accessibility is only enforced at compile-time and serves as a warning to the developer's original intent of making it private.

As an illustration, let's add the public accessibility modifier to the constructor argument, name, and a private accessibility modifier to the member, color. When we add public or private accessibility to an argument of the constructor, that argument automatically becomes a member of the class with the relevant accessibility modifier.

errors in app

Similarly, adding the public accessibility modifier can be applied to the other arguments of the constructor that is the width and height as shown below:

Inheritance

Finally, you can extend an existing class and create a derived class from it with the extends keyword. Let's append the following code to the existing file, class.ts, and compile it:

A few things are happening with the derived Shape3D class:

  • Because it is derived from the Shape class, it inherits the area and color properties.
  • Inside the constructor method, the super method calls the constructor of the base class, Shape, passing the name, width, and height values. Inheritance allows us to reuse the code from Shape, so we can easily calculate this.volume with the inherited area property.
  • The method shoutout() overrides the base class's implementation, and a new method superShout() directly calls the base class's shoutout() method by using the super keyword.

With only a few additional lines of code, we can easily extend a base class to add more specific functionality and make our intention known through TypeScript.

extending the base class

We're Just Getting Started

Trying out TypeScript is easy. If you enjoy a more statically typed approach for large applications, then TypeScript's features will enforce a familiar, disciplined environment. Although it has been compared to CoffeeScript or Dart, TypeScript is different in that it doesn't replace JavaScript; it adds features to JavaScript.

Although Microsoft has promised to keep TypeScript's many capabilities (excluding type annotations) in line with ECMAScript 6, the future development of the language is still unknown. So, if you'd like to try out many of the ES6 features, TypeScript is an excellent way to do so. Go ahead—give it a try!

This post has been updated with contributions from Anisat Akinbani. Anisat is a front-end engineer who loves building web interfaces. She is also a technical writer and loves contributing to open-source projects.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.