...

/

Typed Classes

Typed Classes

Build robust, encapsulated TypeScript classes using clear typing and precise access control.

TypeScript classes help us model real-world entities with precise fields, typed behavior, and controlled access. If you're coming from JavaScript, this removes the uncertainty of runtime design. If you're already thinking in types, this brings structure and safety to your models.

By the end of this lesson, we'll be writing classes that are structured, type-safe, and ready for real-world use.

Why classes—and why TypeScript makes them better

In JavaScript, classes are flexible, but that flexibility cuts both ways. We can forget to initialize a property. Mistype a method parameter. Accidentally expose internal state. And we won’t find out until runtime—if we’re lucky.

TypeScript closes those gaps. With strict mode enabled, which we’ve done throughout this course, we get guarantees that make our class designs safer, clearer, and more robust:

  • Fields are guaranteed to be initialized—either inline or in the constructor, so we never deal with half-formed objects.

  • Methods are fully type checked—we get immediate feedback if parameters are wrong or return values don’t match expectations.

  • Access modifiers give us precise control—we define what’s exposed and what’s internal, making our APIs harder to misuse.

  • Constructors are validated at compile time—we know exactly what’s required to build a valid instance.

This isn’t only about safety—it’s also about clarity. It ensures that the structure we define is the structure we get, consistently and reliably.

Defining a class with typed fields

We’ve all worked with classes in JavaScript. TypeScript builds on that familiar foundation by adding explicit types, guaranteed initialization, and strict enforcement of method contracts.

We declare fields with clear types. We use constructors to ensure proper setup. And we define methods with fully typed inputs and return values—giving us predictable, verifiable behavior from the start.

Let’s walk through a complete example.

Press + to interact
TypeScript 5.8.3
Files
class User {
name: string;
email: string;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
greet(): string {
return `Hello, ${this.name}!`;
}
}
const user = new User("Ada Lovelace", "ada@example.com");
console.log(user.greet());

Explanation:

    ...
    Access this course and 1400+ top-rated courses and projects.