SoFunction
Updated on 2025-03-01

Detailed explanation of the basic concepts and usage of classes in TypeScript

introduction

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

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

Class Basics

In TypeScript, a class is a blueprint for creating an object that defines the properties and methods of an object. The core concepts of object-oriented programming can be implemented using classes: encapsulation, inheritance, and polymorphism.

Define the class

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

class Animal {
  name: string;
  constructor(name: string) {
     = name;
  }
  sayHello() {
    (`I am ${}`);
  }
}

The above code defines a name calledAnimalclass, it has a class callednameand a property namedsayHellomethod. ConstructorconstructorThe properties used to initialize the class.

Create an object

An instance of an object can be created through a class. We can usenewKeywords to create instances of the class and then access the properties and methods of the object. Here is an example:

const cat = new Animal("Meow");
(); // Output:I'm Meow

The above code creates a name calledcatofAnimalAn instance of the class and called itssayHellomethod.

Inheritance of classes

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 useextendsKeywords to achieve inheritance.

Let's create aCatclass, it inherits fromAnimalkind:

class Cat extends Animal {
  // You can add properties and methods that are unique to the Cat class}

Through inheritance,CatClass inheritedAnimalWe can also use the properties and methods of the class toCatAdd cat-specific properties and methods to the class.

Rewriting method

In a subclass, we can rewrite from the parent

Methods inherited from classes to realize behaviors unique to subclasses. In TypeScript, we can usesuperKeywords to call the parent class's method.

class Cat extends Animal {
  sayHello() {
    (); // Call the parent class's sayHello method    ("Meow");
  }
}

In the above code,CatClass rewrittensayHelloMethods and use them in the method()Called the parent classAnimalofsayHellomethod. In this way, the subclass can add its own behavior based on inheriting the parent class method.

Access modifier

In the class, we can use access modifiers to control access rights of properties and methods. TypeScript provides three access modifiers:publicprivateandprotected

  • public: Public, accessible inside and outside the class.
  • private: Private, only accessible inside the class.
  • protected: Protected, accessible within and in derived classes.

By default, the properties and methods of the class arepublicAccess modifier.

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

In the above code,nameThe attributes are public,ageThe attributes are private.colorAttributes are protected.

Abstract Class

An abstract class is a class that cannot be instantiated directly, and it can only be used as the base class of other classes. Abstract classes can contain abstract methods and implementations of concrete methods.

In TypeScript, we can useabstractKeywords to define abstract classes and abstract methods.

abstract class Animal {
  abstract makeSound(): void;
  move(): void {
    ("The animals are moving");
  }
}

In the above code,AnimalA class is an abstract class, it has an abstract methodmakeSoundAnd a specific methodmove. Abstract methods are not implemented in concrete terms, but are implemented by derived classes.

Interface implementation

An interface is a way of describing an object's shape, which defines the properties and methods an object should have. In TypeScript, we can use interfaces to implement class constraints.

interface Shape {
  calculateArea(): number;
}
class Circle implements Shape {
  radius: number;
  constructor(radius: number) {
     = radius;
  }
  calculateArea() {
    return  *  * ;
  }
}

In the above code,Shapeis an interface that defines acalculateAreamethod.CircleThe class has been implementedShapeinterface and provide specific implementations.

Class Advanced

In the previous content, we introduced the basic concepts and usage of classes in TypeScript. Now, let's dive into some more exploring the features and techniques of classes.

Type annotation

Type annotation in TypeScript is a way to label types on variables, parameters, and return values. Through type annotations, we can make the code clearer and catch some potential errors during the compilation phase.

In a class, we can use type annotations to declare the type of the property and the parameter type of the method and the return value type.

class Circle {
  radius: number;
  constructor(radius: number) {
     = radius;
  }
  calculateArea(): number {
    return  *  * ;
  }
}

In the above code,radiusProperties andcalculateAreaMethods all use type annotations to clarify their types.

Type inference

TypeScript's type system has the ability to type inference, which can automatically infer the type of expression based on the context. In a class, if we do not explicitly declare the type, TypeScript will automatically infer the type of the property based on the assignment statement.

class Circle {
  radius = 0; // Type inferred as number  constructor(radius: number) {
     = radius;
  }
}

In the above code, we do not explicitly declareradiusTypeScript will automatically infer its type based on the assignment statementnumber

Generic Classes

Generics are a way to use type parameters in your code, which enhances the flexibility and reusability of your code. In TypeScript, we can use generics to create generic classes.

Let's look at a simple example to implement a generic stack class:

class Stack<T> {
  private items: T[] = [];
  push(item: T) {
    (item);
  }
  pop(): T {
    return ();
  }
}

In the above code,StackThe class uses type parametersT, used to represent the element type in the stack. In this way, we can useStackThe specific type of element is specified in the class.

Type alias

Type alias is a way to alias a type, which can simplify the expression of complex types. In a class, we can use type alias to define complex attribute types or method parameter types.

type Point = {
  x: number;
  y: number;
};
class Shape {
  position: Point;
  constructor(position: Point) {
     = position;
  }
}

In the above code,Pointis a type alias that represents axandyPoint of attribute.ShapeClassicpositionThe attribute has been usedPointType alias.

Class decorator

A class decorator is a special type 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) {
  
(`kind ${} Been decorated`);
}
@logClass
class MyClass {
  // Class definition}

In the above code,logClassis a class decorator function that is called when the class is declared and outputs the class name.

Summarize

Through this article, we have a deeper understanding of the concepts and usage of classes in TypeScript. We learned how to define classes, create objects, inherit and override methods, and implement them using access modifiers, abstract classes, and interfaces. We also understand advanced features such as type annotation and type inference, generic classes, type alias, and class decorators.

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

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

This is the article about the basic concepts and detailed explanations of classes in TypeScript. For more related TypeScript content, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!