Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Classes in TypeScript | Section
TypeScript for Backend Development

bookClasses in TypeScript

Glissez pour afficher le menu

Classes allow you to create structured objects with properties and methods. They are an important part of TypeScript and are widely used in frameworks like Nest.js.

Creating a Class

A class defines a blueprint for creating objects:

class User {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

You can create an instance of the class:

const user = new User("Alice", 30);

Adding Methods

Classes can include methods that define behavior:

class User {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet(): string {
    return `Hello, ${this.name}`;
  }
}

Access Modifiers

TypeScript allows you to control access to properties:

  • public: accessible everywhere (default);
  • private: accessible only inside the class.
class User {
  private password: string;

  constructor(password: string) {
    this.password = password;
  }
}
question mark

What is the main purpose of a class in TypeScript?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 8

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 1. Chapitre 8
some-alt