TypeScript Classes

Classes are a core concept of object-oriented programming (OOP). They are templates or blueprints for creating objects with the same properties and methods. TypeScript fully supports object-oriented programming, providing features such as classes, inheritance, and access modifiers.

Classes encapsulate data (attributes) and behavior (methods), making code more modular, reusable, and maintainable. Through classes, we can create multiple objects with the same structure, and these objects are called instances of the class.


Class Definition

TypeScript usesclassthe `class` keyword to define a class. A class can contain the following members:

  • Field: A variable declared in the class, representing the object's attributes
  • Constructor: A special method called when the class is instantiated, used to initialize the object
  • Method: A function defined in the class, representing the object's behavior

Syntax Format

class class_name {
    // 字段声明
    field1: type;
    field2: type;

    // 构造函数
    constructor(parameters) {
        // 初始化代码
    }

    // 方法
    methodName(): return_type {
        // 方法实现
    }
}

Example: Creating a Simple Class

Example

// Define an empty Person class
class Person {
}

Compiled JavaScript:

Example

var Person = /** @class */ (function () {
    function Person() {
    }
    return Person;
}());

Class Fields and Constructors

Class fields are where object data is stored, and constructors are automatically called when an object is created to initialize the fields.

Example

// Define the Car class
class Car {
// Fields: attributes describing the car
    engine: string;

// Constructor: initializes engine when creating an object
    constructor(engine: string) {
        this.engine = engine;
    }

// Method: display engine information
    disp(): void {
console.log("Engine model: " + this.engine);
    }
}

// Create an instance of the class
var car = new Car("V8 engine");

// Access a field
console.log("Read engine: " + car.engine);

// Call a method
car.disp();

Output:

读取发动机: V8 发动机
发动机型号: V8 发动机

Explanation:

  • thisThe `this` keyword refers to the current instance of the class.
  • Constructor parameter names can be the same as field names, usingthis.field`this` to distinguish them.
  • Usenewthe `new` keyword to create an instance of the class.

Note:TypeScript classes are converted to JavaScript constructor/prototype patterns after compilation, and interfaces do not appear in the compiled output.


Access Control Modifiers

TypeScript provides three access modifiers to control the accessibility of class members:

Modifier Description
public Public member, accessible from anywhere (default)
private Private member, accessible only within the class
protected Protected member, accessible within the class and its subclasses

public (default)

Example

class Person {
public name: string; // Public attribute
public age: number; // Public attribute

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

    public introduce(): void {
console.log("I am " + this.name + ", " + this.age + " years old");
    }
}

var person = new Person("Alice", 25);
console.log("Name: " + person.name); // Can be accessed
person.introduce(); // Can be accessed

private

Example

class Person {
    public name: string;
private secret: string; // Private attribute, cannot be accessed directly from outside

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

// Public methods can access private attributes
    public revealSecret(): void {
console.log("Secret: " + this.secret);
    }
}

var person = new Person("Alice", "I like programming");

console.log("Name: " + person.name); // Can be accessed
// console.log(person.secret); // Error: 'secret' is a private property

person.revealSecret(); // Access private property through public method

protected

Example

class Person {
protected name: string; // Protected attribute

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

    protected sayHello(): void {
console.log("Hello, I am " + this.name);
    }
}

class Student extends Person {
    private grade: string;

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

    public introduce(): void {
// Subclasses can access protected attributes and methods
console.log("I am " + this.name + ", grade: " + this.grade);
        this.sayHello();
    }
}

var student = new Student("Bob", "Grade 12");
student.introduce(); // Can be accessed

// console.log(student.name); // Error: 'name' is a protected property

Output:

我是 Bob,年级: 高三
你好,我是 Bob

Class Inheritance

Inheritance allows a class (subclass) to acquire properties and methods from another class (parent class). A subclass can reuse the parent class's code and can also extend or override the parent class's behavior.

Basic Syntax

class child_class extends parent_class {
    // 子类新增的属性和方法
}

Single Inheritance

Example

// Parent class: Shape
class Shape {
    area: number;

    constructor(a: number) {
        this.area = a;
    }
}

// Subclass: Circle, inheriting from Shape
class Circle extends Shape {
    disp(): void {
console.log("Circle area: " + this.area);
    }
}

var circle = new Circle(223);
circle.disp();

Output:

圆的面积: 223

Multiple Inheritance

TypeScript does not support multiple inheritance (a class inheriting from multiple classes), but it supports multilevel inheritance (A inherits from B, B inherits from C):

Example

// Root class
class Root {
    str: string;
}

// Subclass: inherits from Root
class Child extends Root {
}

// Leaf class: inherits from Child (multilevel inheritance)
class Leaf extends Child {
}

var leaf = new Leaf();
leaf.str = "hello";
console.log("str value: " + leaf.str);

Output:

str 值: hello

Method Override

A subclass can override a method of the parent class, that is, define a method with the same name as the parent class's method in the subclass to implement its own behavior.

Usesuperthe `super` keyword to call the parent class's method.

Example

// Parent class
class PrinterClass {
    doPrint(): void {
console.log("Parent class's doPrint() method");
    }
}

// Subclass: override parent class method
class StringPrinter extends PrinterClass {
    doPrint(): void {
// Call the parent class's method
        super.doPrint();

// Subclass's own logic
console.log("Subclass's doPrint() method");
    }
}

var obj = new StringPrinter();
obj.doPrint();

Output:

父类的 doPrint() 方法
子类的 doPrint() 方法

Static Members

Usestaticthe `static` keyword to define members that belong to the class itself, not to instances of the class. They can be accessed directly through the class name without creating an instance.

Example

class StaticMem {
// Static attribute
    static num: number;

// Static method
    static disp(): void {
console.log("The value of num is " + StaticMem.num);
    }
}

// Access static members directly through the class name
StaticMem.num = 12;
StaticMem.disp();

Running result:

num 值为 12

Application scenario:Static members are commonly used to define class constants, utility methods, or singleton patterns.


instanceof Operator

instanceofUsed to determine whether an object is an instance of a class.

Example

class Person {
}

var obj = new Person();
var isPerson = obj instanceof Person;

console.log("Is obj an instance of Person? " + isPerson);

Running result:

obj 是 Person 类的实例吗? true

Classes Implementing Interfaces

A class can use theimplementskeyword to implement an interface, ensuring the class conforms to the contract defined by the interface.

Example

// Define interface
interface ILoan {
interest: number; // interest rate
}

// Class implements interface
class AgriLoan implements ILoan {
    interest: number;
rebate: number; // rebate

    constructor(interest: number, rebate: number) {
        this.interest = interest;
        this.rebate = rebate;
    }
}

var loan = new AgriLoan(10, 1);
console.log("Interest rate: " + loan.interest + "%, rebate: " + loan.rebate);

Running result:

利率: 10%,回扣: 1

Abstract Classes

Abstract classes cannot be instantiated, they can only serve as base classes for subclasses to inherit. Abstract classes can contain abstract methods (placeholder methods without implementation), which subclasses must implement.

Example

// Abstract class
abstract class Animal {
abstract makeSound(): void; // Abstract method, must be implemented by subclasses

    move(): void {
console.log("Animal is moving");
    }
}

// Concrete class: inherits abstract class
class Dog extends Animal {
    makeSound(): void {
console.log("Woof woof!");
    }
}

var dog = new Dog();
dog.move();
dog.makeSound();

Running result:

The animal is moving
Woof woof woof!

Comprehensive Example

Comprehensively applying various features of classes:

Example

// Interface definition
interface I Printable {
    print(): void;
}

// Abstract class
abstract class Item {
    protected name: string;
    protected price: number;

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

    abstract getDetails(): string;
}

// Concrete class
class Product extends Item implements I Printable {
    private category: string;

    constructor(name: string, price: number, category: string) {
        super(name, price);
        this.category = category;
    }

// Implement abstract method
    getDetails(): string {
return `Product: ${this.name}, Price: ¥${this.price}, Category: ${this.category}`;
    }

// Implement interface method
    print(): void {
        console.log(this.getDetails());
    }

// Static method
    static create(name: string, price: number): Product {
return new Product(name, price, "Default category");
    }
}

// Usage
var product = Product.create("laptop", 5999);
product.print();

// Discount method
class DiscountedProduct extends Product {
    private discount: number;

    constructor(name: string, price: number, category: string, discount: number) {
        super(name, price, category);
        this.discount = discount;
    }

    getDetails(): string {
        var discountedPrice = this.price * (1 - this.discount / 100);
return `Product: ${this.name}, Original price: ¥${this.price}, Discount: ${this.discount}%, Current price: ¥${discountedPrice.toFixed(2)}`;
    }
}

var discountedProduct = new DiscountedProduct("Phone", 2999, "Electronic products", 20);
discountedProduct.print();

Running result:

产品: 笔记本电脑, 价格: ¥5999, 类别: 默认类别
产品: 手机, 原价: ¥2999, 折扣: 20%, 现价: ¥2399.20

Summary

TypeScript classes provide complete object-oriented programming support:

  • Class definition: Uses the class keyword, includes fields, constructors, and methods
  • Access modifiers: public, private, protected control member access
  • Inheritance: Uses extends to implement class inheritance, supports multi-level inheritance
  • Method overriding: Subclasses can override parent class methods, use super to call the parent class
  • Static members: Use the static keyword, belong to the class itself rather than instances
  • Interface implementation: Use the implements keyword to implement interfaces
  • Abstract classes: Use the abstract keyword, cannot be instantiated, serve as base classes

Classes are the foundation of TypeScript object-oriented programming. Using classes properly can make code more structured and maintainable.

Other extensions