乐闻世界logo
搜索文章和话题

How to declare a class in TypeScript?

1个答案

1

Declaring a class in TypeScript primarily involves using the class keyword and defining the class's constructor, properties, and methods. Here is a simple example:

typescript
class Person { // Properties name: string; age: number; // Constructor constructor(name: string, age: number) { this.name = name; this.age = age; } // Methods describe(): string { return `I am ${this.name}, I am ${this.age} years old.`; } } // Creating an object using the class let person1 = new Person("张三", 30); console.log(person1.describe()); // Output: I am Zhang San, I am 30 years old.

Key Components of a Class:

  1. Properties: Used to define the characteristics of a class, such as name and age in the example above.
  2. Constructor (constructor): A special method primarily used to initialize objects upon creation, assigning initial values to object properties.
  3. Methods: Define the behavior of a class, such as the describe method which provides a description of a person.

Advanced Features of Classes:

  • Inheritance: Using the extends keyword, subclasses can inherit properties and methods from the parent class.
  • Access modifiers: Such as public (public), private (private), and protected (protected), used to restrict access scope.
  • Static properties and methods: Using the static keyword, these properties and methods belong to the class itself rather than to instances of the class.
typescript
class Employee extends Person { private salary: number; // Private property, not directly accessible from outside constructor(name: string, age: number, salary: number) { super(name, age); // Call the parent class constructor this.salary = salary; } describe(): string { // Override the parent class method return `${super.describe()}, my salary is ${this.salary} yuan.`; } // Static method static isEmployee(obj: any): obj is Employee { return obj instanceof Employee; } } let employee1 = new Employee("李四", 40, 5000); console.log(employee1.describe()); // Output: I am Li Si, I am 40 years old, my salary is 5000 yuan. console.log(Employee.isEmployee(employee1)); // Output: true

This example demonstrates how to use classes, inheritance, access modifiers, and static methods in TypeScript.

2024年7月29日 13:31 回复

你的答案