TypeScript OOP: Classes & Objects Tutorial

In this TypeScript tutorial we learn how to group data and behavior into single entities called classes.

We cover what classes and their objects are, how to declare a class, create a new instance of a class and how to access the members of a class.

We also cover class expressions, how to declare and use them.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

Object Oriented Programming is a difficult topic for new programmers to understand. It’s okay if the OOP sections of the tutorial course takes you longer to understand than the others.

Object Oriented Programming: Classes & Objects

Object oriented programming, or OOP for short, is a popular approach to solving problems in programming languages.

OOP is when we treat both data and behavior as a single, reusable unit. We try to model our application after entities in the real world by using classes and objects.

Note: We should compile the following scripts with the compiler flag –target es6 or greater.

What is a class

A class is a blueprint, or recipe for an object. A class defines what every instance of it should contain. As an example, let’s consider a pizza.

Every pizza has:

  • A base
  • A sauce
  • Cheese
  • Toppings

This is our recipe, our class for a pizza. Not every pizza (instance of our class) will have the same toppings, but it will have toppings.

Classes may contain attributes (properties), as well as methods (functions), collectively known as members. As an example, let’s consider a database of users.

Every user has attributes like:

  • A name
  • An age
  • An address
  • A profile picture
  • An email
  • A password etc.

Every user has functionality available to them, like:

  • Change password
  • Upload profile picture
  • Add to cart
  • Logout etc.

We combine our attributes and functionality into this single entity, a class. Every instance of a user will follow the pattern set up in the class but with different attributes.

What is an object

When we use the term object, we’re referring to an instance of a class. A single pizza, or user, that was created from the class blueprint.

Consider an array, an array is a class. When we create an array, we’re actually creating an instance, or object, of the array class.

Once we’ve created that object, we have access to the properties and functions that TypeScript has declared inside the array class. Like like array.length or array.splice().

Example:
// an object of the array class
var shoppingList:string[] = ["Bread", "Milk"];

In the example above, we’ve created an instance of the array class, an object called ‘shoppingList’. Now that we have an object, we have access to its properties and methods.

Example:
// an object of the array class
var shoppingList:string[] = ["Bread", "Milk"];

// using a property of the array class
console.log("There are " + shoppingList.length + " items in the shopping list");

We can create as many instances of a class as we need, each with their own different values, and each having the array.length property.

How to create (declare) a class

To create a class we use the class keyword, followed by a unique name and a code block.

Syntax:
class ClassName {

  // properties
  // methods

}
Example:
class Employee {

  // properties
  name = "Unknown";

  // methods
  walk() {
    console.log("Walking...");
  }

}

In the example above, we declare a class called ‘Employee’, with one attribute and one method (function).

We should note two conventions typically used when naming classes:

  1. We name our classes in the singular. Instead of a class named Cars, we call it Car.
  2. We use Pascal casing. The first letter of the name is uppercase and each new word in the name has its first letter in uppercase. We don’t separate words with underscores.

We don’t have to name our classes this way but it is a good convention to follow. Some enterprises may require you to follow conventions such as these, or their own.

In this tutorial series we will be using this convention.

How to instantitate an object of a class

To create an object instance of a class, we use the new keyword, followed by the name of the class and a pair of open and close parentheses.

We assign the new instance of the class to a variable to be able to use it.

Syntax:
 var object_name = new ClassName();

The parentheses are used with a class constructor, which we explain in more detail further along in this tutorial.

Example:
class Person {

  // properties
  name = "Unknown";

  // methods
  walk() {
    console.log("Walking...");
  }

}

// instantiate
var p1 = new Person();

In the example above we create a new object of the Person class called ‘p1’. The variable can now be used to access the properties and methods of the class.

Unlike functions, classes need to be declared before they can be instantiated or used. Simply put, the instantiation needs to be below the declaration to avoid errors.

How to access members (properties & methods) of a class

We access class properties or methods with what’s known as dot notation. First we write the object name, followed by a dot operator and the property or method we want to access.

Syntax:
object_name.property;

object_name.method();
Example:
class Person {

  // attributes
  name = "Unknown";

  // methods
  walk() {
    console.log("Walking...");
  }

}

// instantiate
var p1 = new Person();

// access method
p1.walk();

In the example above, we call the walk() method of the ‘p1’ object, which prints a message to the console that was set up in the class.

How to declare class expressions

Similar to function expressions, we can declare class expressions. We also use variables to fetch the class, so the class itself is allowed to be either named or unnamed.

Syntax: unnamed class
var expression_name = class {

  // class body
}
Syntax: named class
var expression_name = class ClassName {

  // class body
}
Example:
var person = class {

  // attributes
  name = "Unknown";

  // methods
  walk() {
    console.log("Walking...");
  }

}

The example above produces the same result as the named declaration, earlier in the tutorial.

We can access a class expression by either instantiating it directly with the new keyword, or by assigning it to a variable (thereby creating an object).

Example:
var Person = class {

  // attributes
  name = "Unknown";

  // methods
  walk() {
    console.log("Walking...");
  }

}

new Person().walk();
// or
var p1 = new Person();
p1.walk();

When we instantiate the class expression directly with the new keyword, we must remember to add open and close parentheses behind the expression_name.

The parentheses are used to construct the object, if there is a constructor present in the declaration.

When a class expression is named, we cannot use the class name to access its members. We must use the variable name.

Example:
var Person = class Employee {

  // attributes
  name = "Unknown";

  // methods
  walk() {
    document.write("Walking...");
  }

}

// correct
new Person().walk();

// incorrect, will raise an error
new Employee().walk();

How to define a class constructor method

We can create a method that will allow us to populate properties at the same time as we create an object. It’s similar to instantiating an array.

A constructor method uses two special keywords.

  • constructor
  • this

First, we start by declaring the properties we want to be able to initialize with values.

Example:
class Person {

  firstName;
  lastName;

}

Next, we define the constructor method with the keyword constructor as the method name.

Example:
class Person {

  firstName;
  lastName;

  constructor() {

  }
}

Then, we add the parameters we want to initialize to the parameter list and assign them to our properties.

Example:
class Person {

  firstName;
  lastName;

  constructor(fn:string, ln:string) {

    this.firstName = fn;
    this.lastName = ln;
  }
}

We would expect that we could just assign the value of the method parameter to the property, but we can’t.

We need to prefix the property with the keyword this .

The this keyword represents the calling object. We can think of it this way, when we create an object, that object’s name will replace the this keyword.

How to construct an object

Now that we have our constructor method defined, we can use it to populate our properties with values when we create the object.

To this we add arguments for the parameters in the parentheses of the class name when we create the object.

Syntax:
class ClassName {

  property;

  constructor(param:type) {

    this.property = param;
  }
}

// construct object
// with values
var obj_name = new ClassName(param);
Example:
class Person {

  firstName;
  lastName;

  constructor(fn:string, ln:string) {

    this.firstName = fn;
    this.lastName = ln;
  }
}

var p1 = new Person("John", "Doe");

console.log(p1);

Summary: Points to remember

  • Classes in TypeScript should be compiled with the –target es6 or greater flag.
  • A class in an entity that allows us to group both data and behavior into a single unit.
  • An object is an instance of the class blueprint. If a class is a cookie cutter, an object would be the cookie.
  • A class has to be declared at any stage above its invocation (use).
  • We instantiate a class by creating a new instance object.
  • We access the members of a class through dot notation, where the object name is followed by a dot and then the member we want to access.
  • We can declare class expressions with or without a name.
  • We can instantiate a class expression directly with the new keyword, or by creating an object.
  • When a class expression is named, we cannot use the name to invoke the class expression. Instead we must use the expression name.
  • To create a class constructor we define a method called ‘constructor’ in the class with parameters for the properties we want to initialize with data.
  • The properties that we want to initialize must be declared before we try to use them in the constructor.
  • The this keyword refers to the calling object.