Classes in TypeScript: User and Expense

TypeScript Classes#

A class is an object-oriented programming (OOP) concept that allows for the instatiation (or creation) of objects. In TypeScript, the name of a class is the name of the default constructor (the function called when creating objects of the class) as well as the name of the type of the objects that are created by the constructor.

In the example below, we declare a class User containing two public properties and one public method:

The User constructor takes two parameters: name and age. The type of the parameters has to match the given signature or we'll get an error from the TypeScript compiler. The signature of a function consists of the function name, parameter names, parameter types, and function return type. Below we show correct and incorrect usage of our User class:

Notice we set the type of mike to be User. By doing so, we get type checking for the public properties and methods defined in the User class.

A common pattern that we'll use in FinanceMe is to set internal class properties to private so they are not accessible outside of the class. In order to access the properties, methods are defined for retrieving and updating those properties:

Methods that retrieve properties are conventionally called getters while methods that update properties are called setters.

Here we are referencing the language-agnostic concept of setters and getters and not the JavaScript feature that uses the get and set keywords for intercepting property access/updates in classes.

We dive further into classes and object-oriented patterns later in the book.

Expense Class#

Now that we have a basic understanding of classes in TypeScript, we can implement our first class, Expense.

The Expense class is responsible for representing an expense, which consists of four things:

  • A label

  • An amount

  • A date

  • A unique ID

The label, amount, and date will be passed to the Expense constructor when creating new Expense objects. The unique ID will not be passed to the constructor. Instead, we will assign each Expense object a unique ID upon creation.

 

This page is a preview of Beginners Guide to TypeScript

Start a new discussion. All notification go to the author.