Skip to content

Chapter 5 of 8

Classes & Object-Oriented Programming

Classes in TypeScript follow standard JavaScript class syntax with the addition of type annotations. A class such as class Animal { name: string; constructor(name: string) { this.name = name; } } declares a property and a constructor in familiar ways. The big difference comes with access modifiers: public members are accessible everywhere and serve as the default, private members are accessible only within the declaring class, and protected members are accessible within the class and its subclasses. These modifiers enforce encapsulation at compile time without affecting the runtime behavior of the emitted JavaScript.

Constructors can be written compactly by adding access modifiers directly to their parameters, automatically promoting those parameters into instance properties such as constructor(private name: string) { }. Inheritance works through the extends keyword, and subclasses can call into their parent with super—both as super(...) from the constructor and super.method() from instance methods—to invoke overridden behavior.

Abstract classes take the inheritance model further by serving as bases that cannot be instantiated themselves; they may declare abstract methods that subclasses are required to implement, such as abstract area(): number; inside abstract class Shape. Getters and setters, declared with the get and set keywords, look like properties from the outside but allow custom logic whenever a value is read or written, giving you a clean way to validate or transform data as it crosses the boundary of an instance.

All chapters
  1. 1Introduction to TypeScript & Setup
  2. 2Basic Types & Type System Fundamentals
  3. 3Functions & Collection Types
  4. 4Interfaces, Type Aliases & Object Shapes
  5. 5Classes & Object-Oriented Programming
  6. 6Generics for Reusable Code
  7. 7Modules & Advanced Type-Level Features
  8. 8Strict Mode & Interoperability with JavaScript

Drill it

Reading is not remembering. These come from the Typescript Essentials deck:

Q

What is TypeScript?

TypeScript is a statically typed superset of JavaScript developed by Microsoft that compiles to plain JavaScript code. It adds optional static typing, interface...

Q

How does TypeScript relate to JavaScript?

TypeScript is a superset of JavaScript, meaning all valid JavaScript code is also valid TypeScript. TypeScript code is transpiled to JavaScript, allowing it to...

Q

How do you install TypeScript?

Install TypeScript globally using npm install -g typescript or locally as a dev dependency with npm install typescript --save-dev. Verify installation with tsc...

Q

What is the TypeScript compiler command?

The TypeScript compiler is invoked with tsc. Use tsc file.ts to compile a single file or tsc to compile based on tsconfig.json.