Master TypeScript OOP classes, visibility modifiers (public, private, protected), parameter properties, and interface implements contracts.
Discover how TypeScript infers types automatically and how let versus const declarations shape wide types versus narrow literal types.
TypeScript enhances ES6 classes with explicit property type annotations, access modifiers, parameter property shortcuts, and interface implementation checks.
public (Default): Accessible from anywhere.private: Accessible ONLY inside the defining class.protected: Accessible inside the defining class AND child subclasses.class BankAccount {
public readonly accountId: string;
private balance: number; // Private encapsulated state
constructor(accountId: string, initialDeposit: number) {
this.accountId = accountId;
this.balance = initialDeposit;
}
public deposit(amount: number): number {
this.balance += amount;
return this.balance;
}
public getBalance(): number {
return this.balance;
}
}
Simplify class constructors by placing access modifiers directly in constructor arguments:
// Concise Parameter Property Shortcut!
class User {
constructor(
public readonly id: number,
public username: string,
private secretHash: string
) {} // Properties automatically declared and assigned!
}
implements KeywordEnforce that a class conforms to a specific interface shape:
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(msg: string) {
console.log("[LOG]:", msg);
}
}
private with JS Private Fields (#): TypeScript private is erased at compile time! If you need true runtime privacy in raw JS, use JavaScript private fields (#balance).Use classes for OOP domain models. Next, let's explore Abstract Classes and Polymorphism!