Summary - Classes
- TypeScript course
- Intermediate
- Lesson 5/89
- 4 min
Write a bank account model with classes.
Summary - Classes
A BankAccount class combines owner and balance instance fields, a static totalAccounts counter, a constructor, and a deposit method. The counter increases with each new account.
class BankAccount {
owner: string;
balance: number;
static totalAccounts: number = 0;
constructor(owner: string) {
this.owner = owner;
this.balance = 0;
BankAccount.totalAccounts++;
}
deposit(amount: number): void {
this.balance += amount;
}
}Practice Write a bank account class
Define a BankAccount class: owner: string and balance: number fields, static totalAccounts: number = 0 counter. The constructor(owner: string) sets balance to 0 and increments BankAccount.totalAccounts. A deposit(amount: number): void method adds to balance. Create two accounts, deposit 100 into one, and print balance and totalAccounts.
Starter code
// BankAccount sınıfı tanımla (sahip ve bakiye)
// toplam hesap sayısı sınıf düzeyinde, başlangıç 0
// constructor sahip alır, bakiye 0 yapar, sayaç artar
// deposit metodu bakiyeye ekleme yapar
// iki hesap oluştur, birine 100 yatır
// bakiye ve toplam hesap sayısını yazdırSample solution
class BankAccount {
owner: string;
balance: number;
static totalAccounts: number = 0;
constructor(owner: string) {
this.owner = owner;
this.balance = 0;
BankAccount.totalAccounts++;
}
deposit(amount: number): void {
this.balance += amount;
}
}
const a1 = new BankAccount("Ada");
const a2 = new BankAccount("Bob");
a1.deposit(100);
console.log(a1.balance);
console.log(BankAccount.totalAccounts);Expected output
100 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What type should the balance field be in a BankAccount class?
- string
- boolean
- static
- number Correct answer
Explanation: Balance is a numeric value, so it should be of type number. static is not a type but an access modifier; string and boolean are wrong types.
2 Complete the balance initial value
constructor(owner: string) {
this.owner = owner;
this.balance = ____;
}
constructor(owner: string) {
this.owner = owner;
this.balance = 0;
}
Explanation: When a new account is opened, the balance starts at 0. 1 is the wrong start, "0" is a string (number expected), and null is not a number.
3 Bank account parts
| Term | Meaning |
|---|---|
class BankAccount |
Class definition |
constructor(owner: string) |
Constructor method |
deposit(amount: number) |
Instance method |
static totalAccounts |
Class-level counter |