TypeScript Classes Part II

Welcome to this second tutorial in the series covering classes in TypeScript. The topics covered in this episode is listed below.

TypeScript Classes Tutorial for Beginners How-To Accessor Static

TypeScript Classes Part I – A New Hope (For structured JavaScript)

  1. Classes
  2. Constructors
  3. Scope Modifiers
  4. Parameter Shorthand

TypeScript Classes Part II – C# Strikes Back

  1. Accessors
  2. Static Properties

TypeScript Classes Part III – Return of the Object Hierarchy

  1. Inheritance
  2. Interfaces
  3. Abstract Classes

Disclaimer

The code for this post was written using Visual Studio Code, ASP.NET 5 (dnvm) runtime was rc-1. Node packages TypeScript v1.6.2 and gulp-typescript v2.9.2 were used. The project was setup to compile the TypeScript files with gulp. The code was tested in Microsoft Edge.

If you want to replicate this setup, just download the code from my GitHub repository, link is at the end of the post. If you want to read more about how to setup a TypeScript project in VS Code for ASP.NET 5, read this post.

Developing in TypeScript

Before we start, just a quick tip if you are new to TypeScript and need help getting started. I recommend either using Visual Studio Code or Visual Studio Community Edition. Both are free and excellent development tools. Which one you should select depends on your preferences.

VS Code is more of an editor, fast and light weight, but it won’t really hold your hand during learning. Now recently launched with extension support, with many great extensions already released and the Community working hard on many more 🙂
Download Visual Studio Code.

Visual Studio is a full fledged IDE, it has pretty much everything you need to develop web, Windows applications, apps, etc. And if the functionality isn’t available out of the box, there’s a great extensibility API, enabling loads of excellent third party extensions, most of them free.
Download Visual Studio Community Edition.

Accessors

Like most programming languages, TypeScript has getter and setter methods, also known as Accessors. These accessors are functions enabling you more control over access to an objects members.

Accessor Syntax

The keywords used are get and set, followed by the accessor name. The setter takes a parameter of a type and the getter has no parameter, just a return type. Accessors can be used from within other accessors.

Scope modifiers are optional, omitting them means that the accessors are public. One gotcha is that accessors for a member name must have the same scope, this means you can’t for example have a public get and private set.

Let’s look at an example:

class Droid {
	private holoMessage: string;

	public set holographicMessage(message: string) {
		this.holoMessage = message;
	}

	public get holographicMessage(): string {
		return this.holoMessage;
	}
}

Using Accessors

The functionality of the code in Example 1 doesn’t differ in reality from just having a public member named holoMessage on the class. But if there’s anything we know it’s that holographic Messages should only be displayed for the person they are intended for. Let’s expand the example a bit before looking at using them from a test:

class Droid {
	private holoMessage: string;
	private receiver: string;

	public set holographicMessage(message: string) {
		this.holoMessage = message;
	}

	public get holographicMessage(): string {
		if (!this.receiver) {
			return "Invalid user!";
		}

		if (this.receiver === "Obi-Wan Kenobi") {
			return this.holoMessage;
		}
	}

	public enterPassCode(code: number): void {
		if (code === 1234) {
			this.receiver = "Obi-Wan Kenobi";
		}
	}
}

Now we got some logic running in our get accessor and we can see the syntax of how to use getters and setters. Any one is allowed to set a new holographic message, but only Obi-Wan has the secret pin-code to make the droid play back the holographic message. Let’s run the code with a quick test:

	var droid = new Droid();
	droid.holographicMessage = "Help me Obi-Wan Kenobi, you are my only hope!";

	console.log(droid.holographicMessage);	// "Invalid user!"

	droid.enterPassCode(42);
	console.log(droid.holographicMessage);	// "Invalid user!"

	droid.enterPassCode(1234);
	console.log(droid.holographicMessage);	// "Help me Obi Wan Kenobi, you are my only hope!"

Row 4 and 7 will render “Invalid user!”, because accessing the getter without the correct code won’t work.
However, row 10 will render the correct message after receiving an acknowledged passcode.

Static Properties

Class members declared using the static keyword is going to be members of the constructor function. This means you are able to call them without instantiating a class first. Instance members on the other hand can then not be called from static members.

Static members can be declared using all scope modifiers, public, private and protected.

Let’s look at an example:

class DeathStar {
	static fireSuperLaser(): string {
		return "Wait, we're powering up...";
	}
}

Calling the method is then done without instantiating the class, like this:

console.log(DeathStar.fireSuperLaser());

This is what the transpiled DeathStar class looks like in ES5:

var DeathStar = (function () {
    function DeathStar() {
    }
    DeathStar.fireSuperLaser = function () {
        return "Wait, we're powering up...";
    };
    return DeathStar;
})();

Here we can see the fireSuperLaser function being added to the constructor function and not to the prototype as instance members are.

Get The Code!

All the code from this post is available on my GitHub account in the repository called: TypeScript_Classes_II.

More TypeScript projects

Tutorial on TypeScript Functions: TypeScript Functions

Setting up an Aurelia project in Visual Studio Code with TypeScript: Aurelia and TypeScript from VS Code

Tutorial for setting up a TypeScript – MVC 6 app in VS2015: Getting started: TypeScript 1.5 in Visual Studio 2015

Tutorial for setting up a TypeScript – MVC 6 app in VS Code: Getting started: TypeScript 1.5 in Visual Studio Code

If you are interested in a more advanced setup of a TypeScript – MVC 6 app that uses RequireJS in VS2015, check out this post: Setting up a TypeScript – RequireJS – Gulp – MVC 6 Web Project in Visual Studio 2015 RC

Happy coding! 🙂

TypeScript Classes Part II
Tagged on:                 

2 thoughts on “TypeScript Classes Part II

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.