7 Languages In 7 Days – Day 2: TypeScript

Getting Started


So, in my previous post, I covered one of the most popular OOP (Object Oriented Programming) languages out there today. In this post I will be covering a bit of a strange language, TypeScript. TypeScript is what’s known as a superset language of JavaScript. It allows for the programmer to enforce variable types and provide classes and objects in JavaScript and provides compile time error checking and not run time. A superset language, is a language that is compiled into another language which is then compiled into byte code. The program does not actually interact with the code that the programmer writes, but the code that is returned from the compiler. Crazy right?! In this post I will not be covering TypeScript in depth, but only enough to get a taste. If you want a more in depth look at TypeScript you can check it out here.

Introduction and Variable Typing

Let’s take a look at a real simple representation of an object.

  class Car {
    numberOfWheels: number;
    color: string;
  }

  function describeCar(car : Car){
    return "Number of Wheels: " + car.numberOfWheels + " Color: " + car.color;
  }

  var car = {numberOfWheels: 4, color: "Red"};
  document.body.innerHTML = describeCar(car);

That’s not so bad is it? When you compile your TypeScript code, the JavaScript that is returned is also pretty simple.

  var Car = (function () {
      function Car() {
    }
    return Car;
  })();

  function describeCar(car) {
    return "Number of Wheels: " + car.numberOfWheels + " Color: " + car.color;
  }
  var car = { numberOfWheels: 4, color: "Red" };
  document.body.innerHTML = describeCar(car);

You can also use interfaces instead of classes. Take a look at the code below, it’s functionally the same as the example above, but uses an interface instead of a class. The compiled JavaScript will differ though.

  interface Car {
    numberOfWheels: number;
    color: string;
  }

  function describeCar(car : Car){
    return "Number of Wheels: " + car.numberOfWheels + " Color: " + car.color;
  }

  var car = {numberOfWheels: 4, color: "Red"};
  document.body.innerHTML = describeCar(car);

And the compiled JavaScript for this one will look like this:

  function describeCar(car) {
    return "Number of Wheels: " + car.numberOfWheels + " Color: " + car.color;
  }
  var car = { numberOfWheels: 4, color: "Red" };
  document.body.innerHTML = describeCar(car);

When we run both code examples, our HTML page that we’re targeting will read

Number of Wheels: 4 Color: Red

So what did I just accomplish? I created a simple class and an object of that class in TypeScript! This is the start of everything that can be done with TypeScript. As you can see, variable typing is being enforced in this example. The car object is expecting both a number and a string, and the describe function is expecting an argument of type Car. If the type of the numberOfWheels variable is changed to something other than a number, like a string, TypeScript will return an error:

Argument of type ‘ { numberOfWheels: string; color; string; }’ is not assignable to parameter of type ‘Car’. Types of property ‘numberOfWheels’ are incompatible. Type ‘string’ is not assignable to type ‘number’.

This will still run in JavaScript without returning any errors, but may lead to some very difficult to find bugs. Yes, this is a very simplistic example but think of it this way. If there are hundreds of classes and long chains of function calls, and a string is passed when it should be a number in JavaScript, you’re not going to see any errors until you run it and who knows what will break down stream. Where as with TypeScript, it will throw a compile time error telling you that you are passing a string where you should be passing a number. This would allow you to find the error quickly and prevent a potential day long bug hunt.

Trying Out Encapsulation

Encapsulation is a fundamental concept of OOP. A very basic explanation of encapsulation is that it is used to restrict access to variables and methods within a class. The key to encapsulation is to only expose the methods, properties and classes that are necessary for the program to run correctly. TypeScript does include the standard accessors of Public, Private and Protected. Let’s take a look at some example TypeScript code where we use encapsulation.

  class Car {
    private numberOfWheels: number = 4;
    public color: string;
  }
  var car = { color: "Red"};

And the JavaScript that’s returned?

  var Car = (function () {
    function Car() {
      this.numberOfWheels = 4;
    }
    return Car;
  })();
  var car = { color: "Red" };

You can see how JavaScript handles private variables, but isn’t the TypeScript code so much cleaner? That is the benefit of using such a language, it removes a lot of the ceremony and allows for the developer to write code that is much easier to understand.

Trying Out Inheritance

Inheritance is another important concept that we will look at, I won’t go into detail about what inheritance is but let’s take a look at how to accomplish this important concept in TypeScript. It’s really very simple to link classes in TypeScript with inheritance. Take a look below at the example code.

  class Vehicle {
    public numberOfWheels:number;
    public color:string;
	
    constructor(){}
  }

  class Car extends Vehicle{
    public numberOfpassengers:number;
	
    constructor(){
      super();
      this.numberOfWheels = 4;
      this.color = "red";
      this.numberOfpassengers = 5;
    }
  }

  class Truck extends Vehicle{
    public cargo:string;
	
    constructor(){
      super();
      this.numberOfWheels = 4;
      this.color = "red";
      this.cargo = "boxes";
    }
  }

And the resulting JavaScript?

  var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var Vehicle = (function () {
    function Vehicle() {
    }
    return Vehicle;
  })();
  var Car = (function (_super) {
    __extends(Car, _super);
    function Car() {
        _super.call(this);
        this.numberOfWheels = 4;
        this.color = "red";
        this.numberOfpassengers = 5;
    }
    return Car;
  })(Vehicle);
  var Truck = (function (_super) {
    __extends(Truck, _super);
    function Truck() {
        _super.call(this);
        this.numberOfWheels = 4;
        this.color = "red";
        this.cargo = "boxes";
    }
    return Truck;
  })(Vehicle);

See how much noise there is in JavaScript if you try and do OOP in that language and how much easier it is to read in TypeScript? Inheritance in TypeScript is pretty easy to grasp if you have experience with other programming languages.

Conclusion

So, as you can see TypeScript can do the same basic OOP things that any other OOP language can. TypeScript definitely has a lot going on for it right now, and it should at least be a blip on everyone’s radar. I hope that you have found this post helpful, please check in again when we will be covering C# ! Thank you!

previous post