BeCuriouzLearn something new every day
Classes: Fields That Know Their Types
💡 A TypeScript class binds typed fields to a constructor, and the compiler guarantees every field is assigned and used at its declared type.
A class is a blueprint for creating objects that bundle data (fields) with behaviour (methods). In TypeScript, the twist is that every field must have a type, and the compiler enforces it everywhere. Recall how you annotated variables earlier — a class just annotates the shape of every object it produces.
Declare fields at the top of the class, then initialise them in the constructor — a special method that runs when you write new. The constructor's parameters get their own types, and TypeScript checks that every declared field is actually assigned before the constructor finishes:
class Account {
owner: string;
balance: number;
constructor(owner: string, initial: number) {
this.owner = owner;
this.balance = initial;
}
}
const a = new Account("Sam", 1000);
a.balance; // numberHere a has type Account, and a.balance is a number — access a.owner = 5 and the compiler rejects it. Fields can also have initialisers (balance: number = 0) so you don't need to set them in the constructor. If a field is neither initialised nor assigned in the constructor, TypeScript's strictPropertyInitialization check flags it as an error — its job is to stop you from ever reading an undefined field you forgot to set.