100 Days of TypeScript (Day 6)

On day 5, we looked at how to implement interfaces to say what behaviour a class can have. I said, at the end, that we were moving into the territory of doing inheritance. Today, we are going to look at how we can implement interfaces, inherit from classes and a whole lot more.

What is inheritance?

If you have never worked with an Object Oriented language before, the concept of inheritance might seem a little odd at first but it’s actually pretty straight forward. To explain inheritance, I am going to go back to an old favourite of mine, the guitar. I am going to demonstrate with a “pseudo class” structure, how to use inheritance. (A pseudo-class is one that demonstrates a class, but isn’t written in any particular language). To start with, I am going to look at the properties that a guitar might have.

  • Necks (typically one, but guitarists such as Jimmy Page sometimes used guitars with more than one neck)
    • A neck may have frets
  • Strings
  • Pickups (for electric guitars)
  • Pickup selector (for electric guitars)
  • Volume controls (for electric guitars)
  • Tone controls (for electric guitars)
  • A bridge (the bit that the strings go into in the body of the guitar)
  • Strap connectors
  • A body
  • A manufacturer
  • A make
  • Serial number
  • Sound hole (for acoustic / electro-acoustic guitars)
  • Headstock (the bit at the top of most guitars)
  • Tuners

That’s not an exhaustive list of all of the things that we can use to make a guitar, but it gives us a good starting point. Before I start creating my classes, I need to decide what is common and what is specialised; in other words, anything that all guitars share is a common feature, and things that are specific to a particular type of guitar are specialised. Anything that is common goes into something we call a base class; a base class is something we will inherit from that has properties and behaviours that are shared.

It is very tempting to jump in and say that the starting point here is a guitar, but I am going to take a step back. While I listed properties for a guitar, it is important to remember that a guitar belongs to a family of things we call musical instruments and there are certain features of a guitar that are common across all commercial musical instruments; if I were writing an application for a music shop, I would want to start with those features as the base for my guitars.

Musical Instruments representing the inheritance chain; the instruments are a piano, an electric bass guitar, an electric guitar and a violin with bow.
Musical Instruments as hierarchies

I will start with a MusicalInstrument pseudo class and put the features in there that are common.

Class MusicalInstrument
    Manufacturer
    Make
    SerialNumber
End Class

You might be surprised to see that I haven’t said what type of musical instrument it is that we are dealing with in there. The reason I haven’t done that is down to inheritance; I am going to use inheritance to say what type of instrument it is that I am dealing with so if I wanted to have a Piano class, I might look at that as being a type of Keyboard, which is a type of MusicalInstrument. This would give me something like this.

Class Keyboard InheritsFrom MusicalInstrument
    ... Features common to all keyboard type instruments
End Class

Class Piano InheritsFrom Keyboard
    ... Features that are specific to a piano
End Class

Going back to the guitar scenario, I might want to create my hierarchy like this.

Class Guitar InheritsFrom MusicalInstrument
    Neck
    Headstock
    Tuners
End Class

Class AcounsticGuitar InheritsFrom Guitar
    SoundHole
End Class

Class ElectricGuitar InheritsFrom Guitar
    Pickups
    VolumeControl
    ToneControls
End Class

I’m not going to add every property to these classes, but this should give you an idea as to what the inheritance chain should look like. What we see in all of this is that inheritance is about creating an object from a hierarchy.

Class inheritance with TypeScript

On day 5, I demonstrated how I can use implements to “inherit” from an interface (technically, we call this implementation rather than inheritance but people sometimes think of interface implementation as inheritance). I am now going to demonstrate how to inherit from classes. To make this interesting, I am going to start with the same validation interface that I implemented in the last post.

interface Validate {
  IsValid(): boolean;
}

If you remember, the last post demonstrated the minimum length validation and maximum length validation but there was code that was repeated between the two classes. What I want to do is create a base class that does all that is necessary for the common code. I am going to start with this code.

class LengthValidationBase implements Validate {
  constructor(protected text: string, protected length: number) {}
  IsValid(): boolean {
  }
}

This code will not compile because IsValid doesn’t return anything. I have two choices here. I can either return a default value or I can use “tricks” to avoid returning the value here. The trick that I am going to use is to make this class something called an abstract class. What this means is that this class cannot be created on its own; it must be inherited from, and the inherited classes can be instantiated.

By creating an abstract class, I am able to create an abstract method. What this is, is a piece of code that, effectively, says “I am not going to give you an implementation here, but anything that inherits from me must add its own implementation.” Unsurprisingly, the keyword to make a class or method abstract is, well it’s abstract. With this, my code now looks like this.

abstract class LengthValidationBase implements Validate {
  constructor(protected text: string, protected length: number) {}
  IsValid(): boolean {
    return this.CheckForValidity();
  }

  public Debug() {
      console.log(`Checking whether the length check of ${this.length} for ${this.text} is valid returns ${this.CheckForValidity()}`);
  }

  protected abstract CheckForValidity(): boolean;
}

There are a few things in my class here that I want to talk about. Let’s start with the constructor. In an earlier post, I talked about how I can declare class-level variables directly in the constructor signature. This is one of those really great features that TypeScript gives us that you won’t see in languages like C#. What we haven’t seen before, though, is this funny protected keyword. What does this mean?

If I want something to be visible only inside the class, I mark a method of field as private. This means that I cannot see this variable/method from outside the class. If I inherit from the class, I still can’t see that variable. If you are thinking that I need to see the values in text and length in my derived class (when we inherit from a class, we say that we have derived from the class), you would be correct. The way that we say that a method or function cannot be seen from outside the class, but can be seen from a derived class is to use the protected keyword.

The CheckForValidity method is interesting. This is an abstract method that I am going to call from the IsValid method, giving us the boolean return value that IsValid is expecting. You can see that this does not actually do anything – we can think of this as being a signature or contract that says “when you inherit from me, you must supply an implementation for this method”.

Note: You can only add abstract methods inside abstract classes. If your class isn’t marked as abstract, then you can’t create abstract methods in there.

Here’s a quick question. Do you think I can create a private abstract method? The answer to this is no, if I tried to do this, TypeScript would tell me that I cannot create a private abstract method. The message I would get is The “private” modifier cannot be used with the “abstract” modifier. When you think about it, this makes perfect sense. A private method cannot be seen outside the class, but an abstract method says that the code must be added in an inherited class.

Something you might be wondering about. Why have I added a Debug method? It’s not described in our interface, so why have I added one? I wanted to provide the ability to write out debug information about what the class is doing and, as the ability to debug doesn’t have anything to do with the validation interface. By using a backtick ` instead of an apostrophe ' in the console log, I am able to do something called string interpolation. This is the funny-looking syntax in the string where the values inside ${} are printed out directly.

Let’s revisit our minimum and maximum length validation. By using inheritance, I move from this.

class MinimumLengthValidation implements Validate {
    constructor(private text: string, private minimumLength: number) {}
    IsValid(): boolean {
        return this.text.length >= this.minimumLength;
    }
}

class MaximumLengthValidation implements Validate {
    constructor(private text: string, private maximumLength: number) {}
    IsValid(): boolean {
        return this.text.length <= this.maximumLength;
    }
}

to

class MaximumLengthValidation extends LengthValidationBase {
  protected CheckForValidity(): boolean {
    return this.text.length <= this.length;
  }
}

class MinimumLengthValidation extends LengthValidationBase {
  protected CheckForValidity(): boolean {
    return this.text.length >= this.length;
  }
}

It may not seem like I have removed a lot of code, but that’s not the main reason for doing inheritance. The main reason for inheritance is to remove code duplication. In the code example above, I only have to declare the constructor once. This is a simple and largely trivial example, but it means that any code I write that inherits from my base class results in exactly the same behaviour in building up the class. I have completely removed the IsValid code from my derived classes, by providing an implementation for my abstract method (note that abstract has been removed from the method name here because I am supplying the real code).

Testing the implementation

I am going to test the implementation of my code. To start with, I am going to use the same method to add the validation items that I did in the last post.

const validation: Validate[] = [];
validation.push(new MinimumLengthValidation('ABC12345', 10));
validation.push(new MinimumLengthValidation('ABC12345AB12345', 10));
validation.push(new MaximumLengthValidation('ABC12345', 10));
validation.push(new MaximumLengthValidation('ABC12345AB12345', 10));

We need to pay attention to the fact that I have created this array as an array of Validate instances. This is going to become important to us because, while I am looping over the validation examples here, I want to call the Debug method, but as this isn’t present in my Validate interface, I can’t do this directly.

validation.forEach((val: Validate) => {
    console.log(val.IsValid());
    // We want to call debug but we can't here.
    // val.Debug(); is not going to work
    // Do something clever here.
});

You see that bit where I say I want to do something clever here? What I want to do here is to do something called a cast. What a cast is, is a way to change one type into another. What I want to do here is to cast the Validate implementation into a LengthValidationBase class so that I can call Debug. To do this, I am going to write the following code, where I use the as keyword to say what I want to cast my class to.

const lengthValidation = val as LengthValidationBase;
lengthValidation.Debug();

In future posts, I am going to deal further with casting, because there are all sorts of cool things we can do with it – far more than we can cover in this one post. For the moment, I will leave you with what my code looks like right now.

validation.forEach((val: Validate) => {
    console.log(val.IsValid());
    // We want to call debug but we can't here.
    // val.Debug(); is not going to work
    const lengthValidation = val as LengthValidationBase;
    lengthValidation.Debug();
});

Conclusion

In this article, we have looked at what inheritance is, and how we can apply it with classes. We discussed making classes abstract and using the protected keyword. We also introduced the ability to cast one type to another. As always, the code for this article is available on Github.

Advertisement

100 days of TypeScript (Day 5)

On day 4 of our journey into TypeScript, we looked at how we could use interfaces to act as data types. As I am about to show you, that’s not all that interfaces can do. In this post, I am going to demonstrate how to use interfaces to set up types so that they must have certain behaviours. For the purposes of this post, I am going to create a simple interface to control validation.

Requirements

The requirements for the validation are going to be really straightforward.

  1. The validation will determine whether a string is greater than or equal to a minimum number of characters.
  2. The validation will determine whether a string is less than or equal to a maximum number of characters.
  3. The validation will use a single method called IsValid to determine whether or not the string is valid.

With these simple requirements in place, I am ready to start writing my code.

Before I start writing the code, I want to address something you might be wondering, namely, why have I written my requirements down? The answer to this is straightforward; as a professional developer, I like to know what it is that I am writing. I find that the act of writing requirements down is a great place for me to start solving the problem I am writing the code for.

The implementation

Okay, getting back to the code. One of my requirements was that I wanted a single method called IsValid that my validation code will use. This is where the interface comes in; interfaces do not have any implementation capabilities so I cannot write any actual logic in my interface, I can say what methods I want to use. This is the code for the interface.

interface Validate {
    IsValid(): boolean;
}

So, now I need to do something with the interface. To fulfil my requirements, I am going to create a class that validates whether or not the string is a minimum length and another class to determine whether or not the class is a maximum length. Both of these classes will use the interface; to do this, I need to use implements to say that the class implements the interface.

class MinimumLengthValidation implements Validate {
    constructor(private text: string, private minimumLength: number) {}
    IsValid(): boolean {
        return this.text.length >= this.minimumLength;
    }
}

You will probably notice that the constructor looks unusual. I have declared text and minimumLength in the signature of the constructor. By marking them as private, I have told TypeScript that I want these assigned here. Effectively this code is exactly the same as this.

class MinimumLengthValidation implements Validate {
    private text: string;
    private minimumLength: number;
    constructor(text: string, minimumLength: number) {
        this.text = text;
        this.minimumLength = minimumLength;
    }
    IsValid(): boolean {
        return this.text.length >= this.minimumLength;
    }
}

The maximum length validation looks remarkably similar to this code unsurprisingly.

class MaximumLengthValidation implements Validate {
    constructor(private text: string, private maximumLength: number) {}
    IsValid(): boolean {
        return this.text.length <= this.maximumLength;
    }
}

Testing the code

Having written the validation classes, I am ready to test them. I could write my code like this.

console.log(new MinimumLengthValidation('ABC12345', 10).IsValid()); // Should print false
console.log(new MinimumLengthValidation('ABC12345AB12345', 10).IsValid()); // Should print true
console.log(new MaximumLengthValidation('ABC12345', 10).IsValid()); // Should print true
console.log(new MaximumLengthValidation('ABC12345AB12345', 10).IsValid()); // Should print false

That doesn’t really demonstrate my validation, so let’s take a look at using the Validate interface. I am going to create an array of Validate items.

const validation: Validate[] = [];

What I am going to do now is push the same validation items from the little snippet above into the array.

validation.push(new MinimumLengthValidation('ABC12345', 10));
validation.push(new MinimumLengthValidation('ABC12345AB12345', 10));
validation.push(new MaximumLengthValidation('ABC12345', 10));
validation.push(new MaximumLengthValidation('ABC12345AB12345', 10));

With this in place, I am going to use a loop to work my way through the array and print out whether or not the validation has succeeded.

for (let index = 0; index < validation.length; index++) {
    console.log(validation[index].IsValid());
}

Coda

We have reached the end of using interfaces to describe what behaviours a class can have. We are starting to move into the territory of inheritance, one of the pillars of Object-Orientation. In the next post, I am going to go further into the world of inheritance and this is where we are really going to pick up the pace.

Thank you so much for reading. As always, the code behind this article is available on github.

100 days of TypeScript (Day 4)

Wow. Day 4 already and we have already covered a lot of material in our quest to go from zero to, well not something cliched, with TypeScript. In the last couple of posts, we delved into using classes in TypeScript so, in this post, I would like to take a bit of a diversion and introduce you to interfaces. Now, if you have come from a language such as C# or Java, you probably think that you won’t learn anything new about interfaces here but interfaces in TypeScript are really cool.

Interfaces as data

One of the things you probably noticed when we were looking at classes is that they can have behaviour. In other words, they aren’t just about data, they also give you the ability to add functionality to manipulate the data. That is incredibly useful but sometimes we want the ability to create something to represent just the data itself. We want to be able to create a type-safe representation of some useful piece of data. You have probably jumped ahead already and thought “I bet Pete’s going to say that interfaces can solve this for me”, and you would be right.

For this post, we are going to create something that represents an email message. We will be able to add recipients, a subject, and the message itself. I am going to start off by writing an interface to represent a single recipient. To create an interface, I change the class keyword for interface so my recipient will look just like this.

interface Recipient {
    email: string;
}

If I wanted to create an instance of a recipient, I could do something like this.

const recipient: Recipient = { email: 'peter@peter.com' };

Variable declarations

As a side note, you will have seen that I have been declaring variables using the const keyword but I have not actually explained where it comes from or what it means. When I started talking about TypeScript, I briefly covered that it was developed to compile to JavaScript. JavaScript has three ways of declaring variables, var, let and const. Originally, JavaScript only had one way, using var, but this was highly problematic. A little while back, let and const were introduced to be a better, less troublesome form of declaration.

Let’s take a look at why var is such an issue. The issue is down to something called block scope. Block scope refers to where a variable can be seen – it should only be visible in the block that it is being declared in so it would probably come as a surprise that the following bit of code lets me see data that it shouldn’t.

for (var i = 0; i < 10; i++) {
  console.log(i);
}
console.log(i); // Wait, why can I see i here?

What we are seeing in this code is var keyword not being covered by the block scope. This can lead to unfortunate side effects in more complicated code because the value becomes unpredictable.

Enter our heroes, let and const.

These were introduced to help us declare variables that respect block scope. We have two keywords because let allows us to declare a variable and then change the value later on, whereas const allows us to declare the variable but it cannot be changed.

Back to our interface

I have created a simple recipient interface and now I am ready to add one that covers the email itself. The email interface will consist of To, CC and BCC recipients lists, as well as the Subject and Message. If we think about things before we start writing code, we make our lives a lot easier so I am going to ensure that the person using the email interface can choose which of the recipients they want to add. As we have a strong type for our recipient, I am going to use a little TypeScript trick and say that the recipients can receive an array of recipients or the recipient can be null using | null.

interface Email {
    To: Recipient[] | null;
    CC: Recipient[] | null;
    BCC: Recipient[] | null;
    Subject: string;
    Message: string;
}

The syntax of Recipient[] | null reads that I want an array of Recipient items OR I want it to be null.

Now that I have my interface, I am going to create a simple function that accepts an Email and write it to the console.

function sendMessage(message: Email) {
    console.log(message);
}
sendMessage(email);

With all the bits and pieces discussed above, you will probably guess that the interface is going to be populated using the const keyword, just like this (this has to go before the sendMessage(email); line).

const email: Email = {
    To: [{
        email: 'bob@bob.com'
    }],
    CC: [{
        email: 'terry@terry.com'
    }, {
        email: 'chris@chris.com'
    }],
    BCC: null,
    Subject: 'This is my email',
    Message: 'This is the message inside my email'
};

Notice that I still had to add the BCC. Without this part, the “shape” of the object would not match the interface and TypeScript is really good at catching things like that.

A quick note about adding individual items to an array. In the recipient entries, each recipient was surrounded by { }. This is how we add an individual entry into the array, so adding multiple ones is simply a matter of separating these { } pairs with a comma.

We have reached the end of our introduction to interfaces. They can do so much more so, in the next post, I am going to show how classes and interfaces work together.

The code for this post can be found on github.

100 Days of TypeScript (Day 1)

Introducing TypeScript

It’s been a while since I’ve had the chance to write in this blog and I really wanted to come up with something different for me. If you’re a long time follower of mine, you probably know that I wrote a book on TypeScript a couple of years ago, so I thought it would be fun for me to embark on one of those 100 Days of types of blog and write a series introducing you to TypeScript if you’ve not used it before; give you a brush up on things you already know if you’ve used it, and maybe introduce you to some new things that you might not have come across before.

Note: This blog series isn’t going to be a continuous 100 days of posting, it’s 100 days by the end.

So, what is TypeScript? If you go to the TypeScript website, the tagline is “TypeScript is JavaScript with syntax for types”. What does that actually mean?

TypeScript was originally built out of the idea that writing high quality JavaScript was difficult. While that’s a subjective opinion, TypeScript rapidly evolved, giving us the ability to use up and coming JavaScript features via polyfills (don’t worry about this, we’ll come back to this in a future post). TypeScript now ranks as one of the most popular languages around.

Getting Started

Okay, you can develop TypeScript apps online in the playground, but I really recommend installing it locally. To do that, you’re going to need to use something like npm, yarn or pnmpm. If you don’t have npm installed, you need to install Node to get it. Assuming you have installed Node, you can install TypeScript with the following command (depends on the package manager you’re using).

npm install -g typescript

It’s time to write our first TypeScript application (all code is available in github).

This is going to be a simple program to add two numbers together. I’m going to use the TypeScript compiler to set some things up ready for when I want to compile my TypeScript code.

tsc --init

This has created a file called tsconfig.json which sets up compiler options that determine what our JavaScript will look like when we’ve compiled it from TypeScript; oh wait, didn’t I mention that TypeScript compiles down to JavaScript? A quick note – I pretty much always use Visual Studio Code for editing my TypeScript; it’s a great choice if you’ve not used it before.

I’m going to add a file called day1.ts to add my TypeScript to add my first piece example. The .ts extension tells us that this is a TypeScript file. If you have used JavaScript before, the code will look familiar to you. This is what our add function would look like as a JavaScript method.

function add(number1, number2) {
    return number1 + number2;
}

I said that I wanted the add function to be able to add two numbers. I don’t want it to add two strings together or a date and a string. This is where the first strength of TypeScript really comes into its own, and where the TypeScript tagline makes sense. I am going to constrain the function to accept numbers and return a number using the following syntax.

function add(number1: number, number2: number): number {
    return number1 + number2;
}

If I attempt to pass something that’s not a number to either of the parameters, I won’t be able to compile the code. I can’t pass “special” values such as undefined or null to either of the parameters. In other words, I have just written something that will protect me from myself.

In order to test my code, I’m going to call the function and pass the output to the console window like this.

console.log(add(10, 20));

After saving the file, I want to “compile” the TypeScript code so that it turns into JavaScript. To do this, I simply run the tsc command with no parameters. This picks up the contents of the tsconfig.json file and uses that to control how the file is compiled. (The tsc command here should be run in the same directory as the tsconfig.json file).

Now that I have compiled my code, I can run it using the following command.

node day1.js

And that’s it; that’s the first TypeScript program. In day 2, we are going to look at how to change our function over so that it sits inside a class; which will let us see how we can start to leverage object oriented concepts to build reusable blocks.