TypeScript Classes
A TypeScript class is a class with types on its fields and its constructor. The compiler checks each stored value against the field type.
Typed fields
The Person class declares two typed fields. Two instances hold different values.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const ada = new Person("Ada", 36);
const ben = new Person("Ben", 41);
console.log(ada.name);
console.log(ada.age);
console.log(ben.name);
console.log(ben.age);A method reads the fields
The describe method builds one line from the fields. The call prints that line.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
describe(): void {
console.log(this.name + " is " + this.age);
}
}
const ada = new Person("Ada", 36);
ada.describe();Example
class BankAccount {
owner: string;
balance: number;
constructor(owner: string, balance: number) {
this.owner = owner;
this.balance = balance;
}
deposit(amount: number): void {
this.balance = this.balance + amount;
}
}
const account = new BankAccount("Ada", 100);
console.log(account.balance);
account.deposit(50);
console.log(account.balance);Key points
- A field declaration gives each field a type.
- Constructor parameters carry types like any other parameters.
- The constructor stores each parameter on the matching field.
- Each instance holds its own field values.
- A method reads the fields of its instance through this.
In this example, the BankAccount class declares an owner field and a balance field. The constructor stores the starting values on the new instance. The first log shows the starting balance of 100. The deposit call adds 50, and the second log shows 150.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does the compiler check in a typed class?