What is class in Typescript

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();

What is class in Typescript – Interview Questions

Q 1: What is a class in TypeScript?

Ans: A class is a blueprint used to create objects. It can contain properties and methods.

Q 2: How do you define a class in TypeScript?

Ans: <pre><code>" . htmlspecialchars( " class Person { name: string; greet() { console.log("Hello"); }}) . "</code></pre>",

Q 3: What is an object in TypeScript?

Ans: An object is an instance of a class.

Q 4: Does TypeScript support constructors?

Ans: Yes, constructors initialize class properties.

Q 5: Can classes be reused?

Ans: Yes, using inheritance.

What is class in Typescript – Objective Questions (MCQs)

Q1. A class in TypeScript is used to create:






Q2. Which keyword is used to define a class?






Q3. A class contains:






Q4. Which method is automatically called when an object is created?






Q5. Creating an object from a class is known as:






Related What is class in Typescript Topics