Basic concepts and usage of TypeScript classes

cover.png

introduction

Front-end students often use JavaScript to build web applications. Although JavaScript is a flexible and powerful language, it may encounter some problems in large-scale projects, such as challenges in type safety, code organization and maintainability. TypeScript, a superset of JavaScript, provides a solution to these problems by introducing static typing and object-oriented concepts.

This article will introduce the concept and usage of classes in TypeScript. I hope it can help you better understand and use the classes in TypeScript.

class base

In TypeScript, a class is a kind of blueprint for creating objects, which defines the properties and methods of the object. Using classes enables the core concepts of object-oriented programming: encapsulation, inheritance, and polymorphism.

define class

In TypeScript, we can use classthe keyword to define a class. Let's look at a simple example:

class Animal {
  name: string;

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

  sayHello() {
    console.log(`我是 ${this.name}`);
  }
}

The above code defines a class Animalnamed with a nameproperty named and a method sayHellonamed . Constructors constructorare used to initialize properties of a class.

create object

Instances of objects can be created through classes. We can use newthe keyword to create an instance of a class and then access the properties and methods of the object. Below is an example:

const cat = new Animal("喵喵");
cat.sayHello(); // 输出:我是喵喵

The code above creates catan Animalinstance of the class called and calls its sayHellomethod .

class inheritance

Inheritance is an important feature of object-oriented programming, which allows us to create a new class and inherit properties and methods from existing classes. In TypeScript, we can use extendsthe keyword to implement inheritance.

Let's create a Catclass that inherits from Animalthe class:

class Cat extends Animal {
  // 可以添加 Cat 类特有的属性和方法
}

通过继承,Cat 类继承了 Animal 类的属性和方法,我们还可以在 Cat 类中添加特定于猫的属性和方法。

方法的重写

在子类中,我们可以重写从父

类继承而来的方法,以实现子类特有的行为。在 TypeScript 中,我们可以使用 super 关键字来调用父类的方法。

class Cat extends Animal {
  sayHello() {
    super.sayHello(); // 调用父类的 sayHello 方法
    console.log("喵喵");
  }
}

上面的代码中,Cat 类重写了 sayHello 方法,并在方法中使用 super.sayHello() 调用了父类 AnimalsayHello 方法。这样,子类可以在继承父类方法的基础上添加自己的行为。

访问修饰符

在类中,我们可以使用访问修饰符来控制属性和方法的访问权限。TypeScript 提供了三种访问修饰符:publicprivateprotected

  • public:公共的,可以在类的内部和外部访问。
  • private:私有的,只能在类的内部访问。
  • protected:受保护的,可以在类的内部和派生类中访问。

默认情况下,类的属性和方法是 public 访问修饰符。

class Animal {
  public name: string;
  private age: number;
  protected color: string;
}

上面的代码中,name 属性是公共的,age 属性是私有的,color 属性是受保护的。

抽象类

抽象类是一种不能直接实例化的类,它只能用作其他类的基类。抽象类可以包含抽象方法和具体方法的实现。

在 TypeScript 中,我们可以使用 abstract 关键字来定义抽象类和抽象方法。

abstract class Animal {
  abstract makeSound(): void;

  move(): void {
    console.log("动物在移动");
  }
}

上面的代码中,Animal 类是一个抽象类,它有一个抽象方法 makeSound 和一个具体方法 move。抽象方法没有具体的实现,而是由派生类来实现。

接口实现

接口是一种描述对象的形状的方式,它定义了对象应该具有的属性和方法。在 TypeScript 中,我们可以使用接口来实现类的约束。

interface Shape {
  calculateArea(): number;
}

class Circle implements Shape {
  radius: number;

  constructor(radius: number) {
    this.radius = radius;
  }

  calculateArea() {
    return Math.PI * this.radius * this.radius;
  }
}

上面的代码中,Shape 是一个接口,它定义了一个 calculateArea 方法。Circle 类实现了 Shape 接口,并提供了具体的实现。

类进阶

在前面的内容中,我们介绍了 TypeScript 中类的基本概念和用法。现在,让我们深入一些探索更多关于类的特性和技巧。

类型注解

TypeScript 中的类型注解是一种在变量、参数和返回值上标注类型的方式。通过类型注解,我们可以让代码更加清晰明了,并在编译阶段捕获一些潜在的错误。

在类中,我们可以使用类型注解来声明属性的类型和方法的参数类型以及返回值类型。

class Circle {
  radius: number;

  constructor(radius: number) {
    this.radius = radius;
  }

  calculateArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

上面的代码中,radius 属性和 calculateArea 方法都使用了类型注解,明确了它们的类型。

类型推断

TypeScript 的类型系统具有类型推断的能力,它可以根据上下文自动推断出表达式的类型。在类中,如果我们没有显式地声明类型,TypeScript 会根据赋值语句自动推断出属性的类型。

class Circle {
  radius = 0; // 类型推断为 number

  constructor(radius: number) {
    this.radius = radius;
  }
}

上面的代码中,我们没有显式地声明 radius 的类型,但 TypeScript 会根据赋值语句自动推断出它的类型为 number

泛型类

泛型是一种在代码中使用类型参数的方式,它增强了代码的灵活性和重用性。在 TypeScript 中,我们可以使用泛型来创建泛型类。

让我们来看一个简单的例子,实现一个泛型的堆栈类:

class Stack<T> {
  private items: T[] = [];

  push(item: T) {
    this.items.push(item);
  }

  pop(): T {
    return this.items.pop();
  }
}

上面的代码中,Stack 类使用了类型参数 T,用于表示堆栈中的元素类型。这样,我们可以在使用 Stack 类时指定元素的具体类型。

类型别名

类型别名是一种给类型起别名的方式,它可以简化复杂类型的表达。在类中,我们可以使用类型别名来定义复杂的属性类型或方法参数类型。

type Point = {
  x: number;
  y: number;
};

class Shape {
  position: Point;

  constructor(position: Point) {
    this.position = position;
  }
}

In the above code, Pointis a type alias used to represent xa ypoint with and attributes. ShapeThe class's positionproperty uses Pointthe type alias.

class decorator

A class decorator is a special type of declaration used to decorate a class. It can be declared before the class declaration and applied to the class's constructor. Class decorators can be used to modify the behavior or metadata of a class.

function logClass(target: any) {
  console.log

(`类 ${target.name} 被装饰了`);
}

@logClass
class MyClass {
  // 类的定义
}

In the above code, logClassit is a class decorator function, which will be called when the class is declared and output the name of the class.

Summarize

Through this article, we have gained a deep understanding of the concept and usage of classes in TypeScript. We learned how to define classes, create objects, inherit and override methods, and use access modifiers, abstract classes, and interface implementations. We also looked at advanced features like type annotations and type inference, generic classes, type aliases, and class decorators.

By using classes and object-oriented programming thinking, we can write front-end code with clear structure and high maintainability.

If you have more questions about classes in TypeScript or want to learn more, please check out the official TypeScript documentation and related tutorials.

references:

The sample code is for illustration of concepts only and may not comply with best practices. In actual development, please adjust according to the specific situation.

Guess you like

Origin juejin.im/post/7245948253492576293