Operation and application of Typescript's class syntax [class]

TypeScript is an object-oriented programming language that extends JavaScript, adding a type system and several other features to it. TypeScript's class syntax makes it easier for developers to use object-oriented programming. This article will introduce the operation and application of TypeScript's class syntax in detail, and provide code case analysis.

1. Basic syntax of class

In TypeScript, the class keyword can be used to define a class. Here is a simple class definition example:

class Person {
    
    
  name: string;
  age: number;

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

  sayHello() {
    
    
    console.log(`Hello, my name is ${
      
      this.name}, and I'm ${
      
      this.age} years old.`);
  }
}

In the above example, we defined a Personclass named with two properties nameand age, as well as a constructor and a method sayHello. The constructor is used to initialize the nameand ageproperties, while sayHellothe method is used to output a greeting.

2. Inheritance and polymorphism

In TypeScript, we can use extendsthe keyword to implement class inheritance. Here is an inheritance example:

class Student extends Person {
    
    
  grade: number;

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

  sayHello() {
    
    
    console.log(`Hello, my name is ${
      
      this.name}, and I'm a student in grade ${
      
      this.grade}.`);
  }
}

In the example above, we defined a Studentclass named that inherits from Personthe class and added a gradeproperty and an overridden sayHellomethod. In the constructor, we use superthe keyword to call the constructor of the parent class.

Through inheritance, we can achieve polymorphism. In the above example, Studentthe class overrides sayHellothe method, which means when we call sayHellothe method, if the object is an instance of the class, then the method in the class Studentwill be called , otherwise the method in the class will be called.StudentPerson

3. Access modifiers

In TypeScript, we can use access modifiers to restrict access to properties and methods of a class. TypeScript supports three access modifiers: public, privateand protected.

  • public: The default access modifier, indicating that properties and methods can be accessed by anyone.
  • private: Indicates that properties and methods can only be accessed within the class.
  • protected: Indicates that properties and methods can be accessed within the class and in subclasses.

Here is an example access modifier:

class Animal {
    
    
  private name: string;
  protected age: number;

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

  sayHello() {
    
    
    console.log(`Hello, my name is ${
      
      this.name}, and I'm ${
      
      this.age} years old.`);
  }
}

class Cat extends Animal {
    
    
  constructor(name: string, age: number) {
    
    
    super(name, age);
  }

  sayHello() {
    
    
    console.log(`Hello, I'm a cat, and I'm ${
      
      this.age} years old.`);
  }
}

const animal = new Animal('Tom', 3);
animal.sayHello(); // 输出:Hello, my name is Tom, and I'm 3 years old.
console.log(animal.name); // 编译错误:属性“name”为私有属性,只能在类“Animal”中访问。

const cat = new Cat('Kitty', 2);
cat.sayHello(); // 输出:Hello, I'm a cat, and I'm 2 years old.
console.log(cat.age); // 输出:2

In the above example, the attribute Animalin the class nameuses privatethe access modifier and therefore can only Animalbe accessed within the class. The ageproperty uses protectedthe access modifier, so it can be accessed Animalinside and Catwithin the class.

4. Abstract classes and interfaces

In TypeScript, we can use abstract classes and interfaces to define the specification of a class. An abstract class is a class that cannot be instantiated, it can only be inherited. An interface is a specification that defines a set of methods and properties that can be implemented by a class. Here is an example of abstract classes and interfaces:

abstract class Shape {
    
    
  abstract area(): number;
}

interface Printable {
    
    
  print(): void;
}

class Rectangle extends Shape implements Printable {
    
    
  width: number;
  height: number;

  constructor(width: number, height: number) {
    
    
    super();
    this.width = width;
    this.height = height;
  }

  area() {
    
    
    return this.width * this.height;
  }

  print() {
    
    
    console.log(`The area of the rectangle is ${
      
      this.area()}.`);
  }
}

const rect = new Rectangle(3, 4);
rect.print(); // 输出:The area of the rectangle is 12.

In the above example, we defined an abstract class Shapeand an interface Printable. ShapeThere is an abstract method in a class area, which must be implemented by subclasses. RectangleThe class inherits Shapethe class and implements Printablethe interface. RectangleThe class implements areamethods and printmethods.

5. Generics

In TypeScript, we can use generics to define classes, functions and interfaces. Generics allow us to specify the type without having to specify a specific type when writing code, but to specify the type when using it. Here is an example of a generic class:

class Pair<T, U> {
    
    
  first: T;
  second: U;

  constructor(first: T, second: U) {
    
    
    this.first = first;
    this.second = second;
  }
}

const pair = new Pair('hello', 123);
console.log(pair.first); // 输出:hello
console.log(pair.second); // 输出:123

In the above example, we defined a generic class Pairwith two type parameters Tand U. When creating Pairan object, we can specify the specific types of Tand U.

6. Summary

This article introduces the operation and application of TypeScript's class syntax in detail, including basic syntax, inheritance and polymorphism, access modifiers, abstract classes and interfaces, and generics. Through these examples, we can better understand and apply TypeScript's class syntax.

Guess you like

Origin blog.csdn.net/weiyi47/article/details/132629049