In TypeScript, a class is a blueprint for creating objects with predefined properties and methods. It is an essential feature of object-oriented programming (OOP) and provides a way to model real-world entities and their behaviors in your code.
Here’s a brief overview of classes in TypeScript:
Class Declaration: A class is declared using the class
keyword, followed by the class name and a body enclosed in curly braces {}
. The class body can contain properties, methods, and constructors.
Properties: These are variables that belong to the class. They define the state of the class instances.
Methods: These are functions that belong to the class. They define the behavior of the class instances.
Constructor: A special method called constructor
is used to initialize class properties. It is called automatically when an instance of the class is created.
Access Modifiers: TypeScript supports public
, private
, and protected
access modifiers to control the visibility of class members.
Here’s a simple example to illustrate the concept of classes in TypeScript:
class Person {
// Properties
private name: string;
private age: number;
}
// Method
public greet(): void {
console.log(Hello, my name is ${this.name} and I am ${this.age} years old.
);
}
}
// Constructor
constructor(name: string, age: number)
{
this.name = name;
this.age = age;
}
// Creating an instance of the Person class
const person1 = new Person('John', 38);
// Calling the greet method
person1.greet(); // Output: Hello, my name is John and I am 38 years old.
Key Points
Class Declaration: class Person { ... }
Properties: name
and age
with private
access modifier.
Method: greet() { ... }
Instance Creation: const person1 = new Person('John', 38);
Method Call: person1.greet();