In late 2012, Microsoft introduced TypeScript, a typed superset for JavaScript that compiles into plain JavaScript. TypeScript focuses on providing useful tools for large scale applications by implementing 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.
Installing the Tools
TypeScript features are enforced only at compile-time.
You'll set up your machine according to your specific platform and needs. Windows and Visual Studio users can simply download the Visual Studio Plugin. If you're on Windows and don't have Visual Studio, give Visual Studio Express for Web a try. The TypeScript experience in Visual Studio is currently superior to other code editors.
If you're on a different platform (or don't want to use Visual Studio), all you need is a text editor, a browser, and the TypeScript npm package to use TypeScript. Follow these installation instructions:
- Install Node Package Manager (npm)
$ curl http://npmjs.org/install.sh | sh $ npm --version 1.1.70
- Install the TypeScript npm package globally in the command line:
$ npm install -g typescript $ npm view typescript version npm http GET https://registry.npmjs.org/typescript npm http 304 https://registry.npmjs.org/typescript 0.8.1-1
- Any modern browser: Chrome is used for this tutorial
- Any text editor: Sublime Text is used for this tutorial
-
Syntax highlighting plugin for text editors
That's it; we are 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 proposed for 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, we will create a basic index.html
file and reference an external script file:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Learning TypeScript</title> </head> <body> <script src="hello.js"></script> </body> </html>
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
:
alert('hello world in TypeScript!');
Next, open the command line interface, navigate to the folder containing hello.ts
, and execute the TypeScript compiler with the following command:
tsc hello.ts
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 exact 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.
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
function area(shape: string, width: number, height: number) { var area = width * height; return "I'm a " + shape + " with an area of " + area + " cm squared."; } document.body.innerHTML = area("rectangle", 30, 15);
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:
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 purposely pass a string value for the width
parameter:
function area(shape: string, width: number, height: number) { var area = width * height; return "I'm a " + shape + " with an area of " + area + " cm squared."; } document.body.innerHTML = area("rectangle", "width", 15); // wrong width type
We know this results in an undesirable outcome, and compiling the file alerts us to the problem with the following error:
$ tsc type.ts type.ts(6,26): Supplied parameters do not match any signature of call target
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 type annotations include bool
or even any
.
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
:
interface Shape { name: string; width: number; height: number; color?: string; } function area(shape : Shape) { var area = shape.width * shape.height; return "I'm " + shape.name + " with area " + area + " cm squared"; } console.log( area( {name: "rectangle", width: 30, height: 15} ) ); console.log( area( {name: "square", width: 30, height: 30, color: "blue"} ) );
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.js
results in no errors. To evoke an error, let's append another line of code to interface.js
with a shape that has no name property and view the result in the console of the browser. Append this line to interface.js
:
console.log( area( {width: 30, height: 15} ) );
Now, compile the code with tsc interface.js
. 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:
Now let's look at the error. It is:
interface.ts(26,13): Supplied parameters do not match any signature of call target: Could not apply type 'Shape' to argument 1, which is of type '{ width: number; height: number; }'
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 new feature being discussed for ECMAScript 6. Arrow functions preserve the value of this
, making it much easier to write and use callback functions. Consider the following code:
var shape = { name: "rectangle", popup: function() { console.log('This inside popup(): ' + this.name); setTimeout(function() { console.log('This inside setTimeout(): ' + this.name); console.log("I'm a " + this.name + "!"); }, 3000); } }; shape.popup();
The this.name
on line seven will clearly be empty, as demonstrated in the browser console:
We can easily fix this issue by using the TypeScript arrow function. Simply replace function()
with () =>
.
var shape = { name: "rectangle", popup: function() { console.log('This inside popup(): ' + this.name); setTimeout( () => { console.log('This inside setTimeout(): ' + this.name); console.log("I'm a " + this.name + "!"); }, 3000); } }; shape.popup();
And the results:
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 the ECMAScript 6 proposal. Let's create another file, called class.ts
, and review the class syntax:
class Shape { area: number; color: string; constructor ( name: string, width: number, height: number ) { this.area = width * height; this.color = "pink"; }; shoutout() { return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared."; } } var square = new Shape("square", 30, 30); console.log( square.shoutout() ); console.log( 'Area of Shape: ' + square.area ); console.log( 'Name of Shape: ' + square.name ); console.log( 'Color of Shape: ' + square.color ); console.log( 'Width of Shape: ' + square.width ); console.log( 'Height of Shape: ' + square.height );
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:
class.ts(12,42): The property 'name' does not exist on value of type 'Shape' class.ts(20,40): The property 'name' does not exist on value of type 'Shape' class.ts(22,41): The property 'width' does not exist on value of type 'Shape' class.ts(23,42): The property 'height' does not exist on value of type 'Shape'
Any JavaScript program is already a TypeScript program.
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.
... private color: string; ... constructor ( public name: string, width: number, height: number ) { ...
class.ts(24,41): The property 'color' does not exist on value of type 'Shape'
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:
class Shape3D extends Shape { volume: number; constructor ( public name: string, width: number, height: number, length: number ) { super( name, width, height ); this.volume = length * this.area; }; shoutout() { return "I'm " + this.name + " with a volume of " + this.volume + " cm cube."; } superShout() { return super.shoutout(); } } var cube = new Shape3D("cube", 30, 30, 30); console.log( cube.shoutout() ); console.log( cube.superShout() );
A few things are happening with the derived Shape3D
class:
- Because it is derived from the
Shape
class, it inherits thearea
andcolor
properties. - Inside the constructor method, the
super
method calls the constructor of the base class,Shape
, passing thename
,width
, andheight
values. Inheritance allows us to reuse the code fromShape
, so we can easily calculatethis.volume
with the inheritedarea
property. - The method
shoutout()
overrides the base class's implementation, and a new methodsuperShout()
directly calls the base class'sshoutout()
method by using thesuper
keyword. - Main Website
- Tutorials and samples
- Live code editor with JavaScript output
- Code Repository for discussions and bug tracking
- What is TypeScript? by the developing team
- List of documentations for TypeScript
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.
TypeScript Resources
Despite TypeScript's extremely young age, you can find many great resources on the language around the web (including a full course coming to Tuts+ Premium!). Be sure to check these out:
We're Just Getting Started
TypeScript supports classes, and their implementation closely follows the ECMAScript 6 proposal.
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.
We have yet to see how TypeScript will evolve, but Microsoft has stated that they will keep its many features (type annotations aside) aligned with ECMAScript 6. So, if you'd like to try out many of the new ES6 features, TypeScript is an excellent way to do so! Go ahead - give it a try!
Comments