← Back to TypeScript Course | Chapter 6: Classes | Lesson 1 of 9

Class Basics

A class is a blueprint for creating objects that contain data and behavior. TypeScript classes use JavaScript class syntax while allowing you to describe properties and methods with types.

Creating a Class

A class is declared with the class keyword and can contain properties for storing data and methods for behavior, giving TypeScript a single place to describe both the shape and the operations available on instances of that class.

Example: Creating a Class

typescript
class Person {
  name: string = "";
  greet() {
    console.log(`Hello, ${this.name}`);
  }
}
const p = new Person();
p.name = "Amara";
p.greet();

Properties in a Class

Properties represent the data stored by an object, and TypeScript lets you specify the type of each property directly in the class body, so any attempt to assign an incompatible value is caught at compile time rather than at runtime.

Example: Properties in a Class

typescript
class Product {
  name: string;
  price: number;
  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }
}
const item = new Product("Pen", 2);
console.log(item.name, item.price);

Methods in a Class

Methods are functions defined inside a class that can access the current object's properties through this, letting behavior stay tied to the data it operates on instead of being scattered as free-standing functions.

Example: Methods in a Class

typescript
class Counter {
  count: number = 0;
  increment() {
    this.count++;
  }
}
const c = new Counter();
c.increment();
c.increment();
console.log(c.count);

Creating Multiple Objects

A class can be used to create many independent objects, each with its own instance properties; changing one object's data never affects another object created from the same class.

Example: Creating Multiple Objects

typescript
class Person {
  constructor(public name: string) {}
}
const a = new Person("Zara");
const b = new Person("Leo");
console.log(a.name, b.name);

Class and Object Relationship

A class describes what an object should contain and do, while an object is an actual instance built from that description — the same relationship as a blueprint to a building, where one blueprint can produce many separate buildings.

Example: Class and Object Relationship

typescript
class Car {
  constructor(public model: string) {}
}
const myCar = new Car("Sedan"); // an object built from the Car blueprint
console.log(myCar.model);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.