TypeScript Classes
TypeScript Classes: Access Modifiers, Contracts, and abstract
TypeScript enhances ES6 JavaScript classes with compile-time access modifiers (public, private, protected, readonly), parameter properties, interface implementation (implements), and abstract base classes.
These checks catch invalid internal property access during compilation while emitting clean standard JavaScript classes.
Parameter Properties and Access Modifiers
Adding public, private, protected, or readonly directly inside constructor parameters declares and assigns the class field in one step without boilerplate.
interface Printable {
summary(): string;
}
class BankAccount implements Printable {
constructor(
public readonly owner: string,
private balance: number = 0
) {}
deposit(amount: number): number {
if (amount <= 0) throw new Error("Amount must be positive");
this.balance += amount;
return this.balance;
}
summary(): string {
return `${this.owner}: $${this.balance.toFixed(2)}`;
}
}
const acct = new BankAccount("Maya", 100);
acct.deposit(45);
console.log(acct.summary());
private vs JavaScript #private Fields
TypeScript's private keyword blocks external access only at compile time. JavaScript's #balance hash syntax enforces true privacy at runtime inside the V8/browser engine too.
Common Mistakes to Avoid
- Assuming
privatehides properties inJSON.stringify()or DevTools: TypeScriptprivatefields still exist as normal properties at runtime; use#fieldfor real runtime encapsulation. - Forgetting
overridewhen overriding parent methods: Enable"noImplicitOverride": trueand mark child overrides withoverrideso renamed parent methods never leave dead code silently. - Calling
abstractclasses withnew: Abstract classes serve only as blueprints for subclasses and cannot be instantiated directly.
Frequently Asked Questions
What is the difference between private and protected?
private restricts access strictly to the declaring class, while protected allows subclasses (extends) to read and call that member too.
Can a class implement multiple interfaces?
Yes. Write class Service implements Logger, Disposable { ... } separated by commas.
When should I use a plain object + functions instead of a class?
In React and functional TypeScript apps, plain typed objects and pure functions serialize cleanly to JSON and require less boilerplate unless you genuinely encapsulate mutable state.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.