Search⌘ K
AI Features

Introduction to Classes

Explore TypeScript classes by learning how to create class definitions with properties and methods. Understand error handling for uninitialized properties and how to use the this keyword to access class members effectively.

Classes in TypeScript

A class is the definition of an object, what data it holds, and what operations it can perform. Classes and interfaces form the cornerstone of object-oriented programming.

Let’s take a look at a simple class definition in TypeScript as follows:

TypeScript 4.9.5
// Defining a class named SimpleClass
class SimpleClass {
// Property named "id" with type number
id: number;
// Method named "print" with return type void
print(): void {
console.log(`SimpleClass.print() called.`);
}
}
Defining a simple TypeScript class

Here, we define a class using the class keyword, which is named SimpleClass, and has an id property of type number and a print function, which logs a message to the console.

Notice anything wrong with this code? Well, the compiler generates an error message. ...