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:

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:
import truncate from '../utils/truncate';
import genUniqueId from '../utils/genUniqueId';
import Expense from './Expense';
class Budget {
private label: string;
private limit: number;
private id: string;
constructor(
label: string,
limit: number,
) {
this.updateLabel(label);
this.updateLimit(limit);
this.id = genUniqueId();
}
getId(): string {
return this.id;
}
getLabel(): string {
return this.label;
}
updateLabel(label: string) {
this.label = truncate(label, 15);
}
getLimit(): number {
return this.limit;
}
updateLimit(limit: number): void {
this.limit = limit;
}
}
export default Budget;
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:
enum Category {
Food,
Entertainment,
Housing,
Utilities,
Transportation,
Misc,
}
export default Category;
We can use the name of our enum, Category
, as a type whenever we expect a Category
member to be used:
import Category from './enums/Category';
let myCategory: Category;
myCategory = Category.Food; // OK
myCategory = Category.Housing; // OK
myCategory = ''; // Error
myCategory = 'Food'; // Error
myCategory = 0; // OK
myCategory = 100; // OK
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