Classes in TypeScript: User and Expense
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:
User constructor takes two parameters:
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
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
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.
setkeywords for intercepting property access/updates in classes.
We dive further into classes and object-oriented patterns later in the book.
Now that we have a basic understanding of classes in TypeScript, we can implement our first class,
Expense class is responsible for representing an expense, which consists of four things:
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.