A class is a blueprint for creating objects, providing initial values for state (properties) and functionality (methods).

Example 1: Defining a Class

class Greeter {
  greeting: string;
 
  constructor(message: string) {
    this.greeting = message;
  }
 
  greet() {
    return "Hello, " + this.greeting;
  }
}
 
let greeter = new Greeter("world");
  • greeting is a class property.
  • The constructor initializes the object with a message that gets assigned to the greeting property.
  • greet is a method that returns a greeting message using the greeting property.

Key Points:

  1. Class Definition: A class is defined using the class keyword, followed by its name (Greeter).
  2. Constructor: The constructor method is a special method used to initialize new objects. It is called when creating an instance using new.
  3. Methods: The class can have methods like greet() that define the behavior of the class.
  4. Instance Creation: The new Greeter("world") creates a new instance of the Greeter class, passing "world" to the constructor.