Object Oriented TypeScript

Introduction#

Object Oriented Programming (OOP for short) is a programming paradigm that models problems as a series of communicating objects. In classical OOP, these objects are created using classes, which serve as blueprints for an object's data and behavior. The data is saved in properties while the behavior is saved in methods.

Thinking about problems as a series of communicating objects is useful because it resembles how we think about problems in the real world. For example, imagine creating a scheduling program for a university. Designing a class hierarchy containing a Student, Professor, and University feels natural because real world objects map to software objects.

Prior to ES2015, JavaScript did not have a syntax for classes (although you could simulate them using functions). The TypeScript team considered classes to be an important feature for building scalable applications, so classes were supported from the start as part of TypeScript's initial release in 2012, several years before the ES2015 spec was finalized.

This chapter is divided into two parts. To start, we'll discuss how TypeScript enables five important OOP concepts: encapsulation, abstraction, inheritance, composition, and polymorphism. If you're not familiar with these terms, not to worry--we provide simple definitions alongside concrete examples. In the second part we'll apply these concepts by creating a real project.

To run the code in this chapter, we will use ts-node. If you have not installed TypeScript or ts-node, please see the Setting Up Your Environment section in Chapter 1.

For ease of running the code, we suggest you create a scratch.ts file where you can code along with the provided examples. To run the code in scratch.ts, use the terminal to navigate to the directory where scratch.ts lives and run the following command:

OOP Concepts in TypeScript#

Encapsulation#

Encapsulation is about organizing related data and functions into one class. The data is saved in properties while the functions that operate on that data are saved in methods. Access modifiers determine whether a property or method is public, private, or protected. public means the property/method is accessible outside the class. private means the property/method is only accessible within the class. protected means the property/method is only accessible within the class and within any children that extend the class. Below is an example of how we would use all these modifiers.