Generating the Budget Class#

Budget Class#

In the previous section, we learned the basics of creating and using classes in TypeScript. In this section, we will build on those topics to create a new Budget class.

The Budget class is responsible for representing a budget that consists of four things:

  • A label

  • A limit

  • A category (i.e. clothing, transportation, food)

  • A collection of expenses that fall under that budget

The class diagram below lists the ten methods that Budget will expose:

Budget Class Diagram

The following five methods are very similar to methods we already implemented in the Expense class:

  • getId()

  • getLabel()

  • updateLabel()

  • getLimit()

  • updateLimit()

These are essentially one-line setters and getters for properties on the Budget class:

Five New Methods#

Implementing the remaining five methods below will take a little more work as they use syntax we have not yet seen:

  • getCategory()

  • updateCategory()

  • getExpenses()

  • getExpenseTotal()

  • getIsOverBudget()

The first two methods above deal with a Category type that we have not defined. In this case, Category represents a pre-defined set of budget categories that we define using an enum.

An enum holds a set of named members. We can think of an enum as a collection or grouping of constants. The enum's name can be used as a type in locations where we expect any of its members to be used.

Category enum#

Below we define a Category enum containing 6 members and save it in a file under the top-level enums folder:

We can use the name of our enum, Category, as a type whenever we expect a Category member to be used:

Notice that, perhaps unexpectedly, we can assign any numeric value to the myCategory variable above. This is expected behavior as enum members are by default given a numeric value, starting from 0, incrementing by one as members are added to the list. This has the following implication for our enum members:

 

This page is a preview of Beginners Guide to TypeScript

Please select a discussion on the left.