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:
typescriptclass 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:
- Properties: Used to define the characteristics of a class, such as
nameandagein the example above. - Constructor (
constructor): A special method primarily used to initialize objects upon creation, assigning initial values to object properties. - Methods: Define the behavior of a class, such as the
describemethod which provides a description of a person.
Advanced Features of Classes:
- Inheritance: Using the
extendskeyword, subclasses can inherit properties and methods from the parent class. - Access modifiers: Such as
public(public),private(private), andprotected(protected), used to restrict access scope. - Static properties and methods: Using the
statickeyword, these properties and methods belong to the class itself rather than to instances of the class.
typescriptclass 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 回复