TypeScript Classes
A class is a core concept of object-oriented programming (OOP); it is a template or blueprint for creating objects with the same properties and methods. TypeScript fully supports object-oriented programming and provides features such as classes, inheritance, and access modifiers.
A class encapsulates data (properties) and behavior (methods), making code more modular, reusable, and maintainable. Through classes, we can create multiple objects with the same structure; these objects are called instances of the class.
Definition of the class
TypeScript uses the class keyword to define a class. A class can contain the following members:
- Fields (Field): variables declared in a class, representing the properties of an object
- Constructors (Constructor): a special method called when a class is instantiated, used to initialize the object
- Methods: functions defined in a class, representing the behavior of an object
Syntax format
class class_name {
// Field declaration
field1: type;
field2: type;
// Constructor
constructor(parameters) {
// Initialize code
}
// 方法
methodName(): return_type {
// Method implementation
}
}
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; the constructor is called automatically when an object is created and is used to initialize the fields.
Example
// Define the Car class
class Car {
// Fields: describe the properties of a car
engine: string;
// Constructor: initializes engine when the object is created
constructor(engine: string) {
this.engine = engine;
}
// Method: displays engine information
disp(): void {
console.log("Engine model: " + this.engine);
}
}
// Create an instance of the class
var car = new Car("V8 engine");
// Access fields
console.log("Read engine: " + car.engine);
// Invoke methods
car.disp();
Running result:
读取发动机: V8 发动机
发动机型号: V8 发动机
Explanation:
thisThe keyword refers to the instance of the current class- Constructor parameter names can be the same as field names; use
this.fieldto distinguish them - Use
newThe keyword creates an instance of a class
Note:TypeScript classes are converted to JavaScript's constructor/prototype pattern 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:
| Modifiers | Description |
|---|---|
public |
Public members, accessible anywhere (default) |
private |
Private members, accessible only inside the class |
protected |
Protected members, accessible inside the class and in child classes |
public (default)
Example
class Person {
public name: string; // public property
public age: number; // public property
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); // accessible
person.introduce(); // accessible
private
Example
class Person {
public name: string;
private secret: string; // private property, cannot be accessed directly from outside
constructor(name: string, secret: string) {
this.name = name;
this.secret = secret;
}
// A public method can access a private property
public revealSecret(): void {
console.log("Secret: " + this.secret);
}
}
var person = new Person("Alice", "I like programming");
console.log("Name: " + person.name); // accessible
// console.log(person.secret); // Error: 'secret' is a private property
person.revealSecret(); // access a private property through a public method
protected
Example
class Person {
protected name: string; // protected property
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 {
// Child classes can access protected properties and methods
console.log("I am " + this.name + ", grade: " + this.grade);
this.sayHello();
}
}
var student = new Student("Bob", "Senior 3");
student.introduce(); // accessible
// console.log(student.name); // Error: 'name' is a protected property
Running result:
我是 Bob,年级: 高三
你好,我是 Bob
Class Inheritance
Inheritance allows a class (child class) to acquire properties and methods from another class (parent class). A child class 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 {
// Attributes and methods added by the subclass
}
Single inheritance
Example
// Parent class: Shape
class Shape {
area: number;
constructor(a: number) {
this.area = a;
}
}
// Child class: Circle, inherits from Shape
class Circle extends Shape {
disp(): void {
console.log("Circle area: " + this.area);
}
}
var circle = new Circle(223);
circle.disp();
Running result:
圆的面积: 223
Multi-level inheritance
TypeScript does not support multiple inheritance (a class inheriting from several classes), but it supports multi-level inheritance (A inherits from B, and B inherits from C):
Example
// Root class
class Root {
str: string;
}
// Child class: inherits from Root
class Child extends Root {
}
// Leaf class: inherits from Child (multi-level inheritance)
class Leaf extends Child {
}
var leaf = new Leaf();
leaf.str = "hello";
console.log("str value: " + leaf.str);
Running result:
str 值: hello
Method overriding (Override)
A child class can override a parent class's method, that is, define a method with the same name as the parent's in the child class to implement its own behavior.
Use super The keyword can call a parent class's method.
Example
// Parent class
class PrinterClass {
doPrint(): void {
console.log("The parent class's doPrint() method");
}
}
// Child class: override the parent class method
class StringPrinter extends PrinterClass {
doPrint(): void {
// Call the parent class's method
super.doPrint();
// The child class's own logic
console.log("The child class's doPrint() method");
}
}
var obj = new StringPrinter();
obj.doPrint();
Running result:
父类的 doPrint() 方法
子类的 doPrint() 方法
Static Members
Use static Members defined with the keyword belong to the class itself rather than to an instance of the class. They can be accessed directly through the class name without creating an instance.
Example
class StaticMem {
// Static property
static num: number;
// Static method
static disp(): void {
console.log("num value is " + StaticMem.num);
}
}
// Access static members directly through the class name
StaticMem.num = 12;
StaticMem.disp();
Running result:
num 值为 12
Application scenarios:Static members are often used to define class constants, utility methods, or the singleton pattern.
instanceof operator
instanceof Used to determine whether an object is an instance of a certain class.
Example
class Person {
}
var obj = new Person();
var isPerson = obj instanceof Person;
console.log("Is obj an instance of the Person class? " + isPerson);
Running result:
obj 是 Person 类的实例吗? true
A class implements an interface
A class can use the implements keyword to implement an interface, ensuring that the class conforms to the contract defined by the interface.
Example
// Define an interface
interface ILoan {
interest: number; // interest rate
}
// A class implements the 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
An abstract class cannot be instantiated and can only serve as a base class for child classes to inherit from. An abstract class can contain abstract methods (placeholder methods without implementation), which child classes must implement.
Example
// Abstract class
abstract class Animal {
abstract makeSound(): void; // abstract method, must be implemented by child classes
move(): void {
console.log("The animal is moving");
}
}
// Concrete class: inherits from the abstract class
class Dog extends Animal {
makeSound(): void {
console.log("Woof woof woof!");
}
}
var dog = new Dog();
dog.move();
dog.makeSound();
Running result:
动物在移动
汪汪汪!
Comprehensive example
A comprehensive application of the 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 the abstract method
getDetails(): string {
return 产品: ${this.name}, 价格: ¥${this.price}, 类别: ${this.category};
}
// Implement interface methods
print(): void {
console.log(this.getDetails());
}
// Static method
static create(name: string, price: number): Product {
return new Product(name, price, "Default category");
}
}
// Use
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 产品: ${this.name}, 原价: ¥${this.price}, 折扣: ${this.discount}%, 现价: ¥${discountedPrice.toFixed(2)};
}
}
var discountedProduct = new DiscountedProduct("Phone", 2999, "Electronics", 20);
discountedProduct.print();
Running result:
产品: 笔记本电脑, 价格: ¥5999, 类别: 默认类别
产品: 手机, 原价: ¥2999, 折扣: 20%, 现价: ¥2399.20
Summary
TypeScript's classes provide complete support for object-oriented programming:
- Definition of the class: use the class keyword, including fields, constructors, and methods
- access modifiers: public, private, and protected control member access
- inheritance: use extends for class inheritance, supporting multi-level inheritance
- Method Overriding: child classes can override parent class methods and use super to call the parent class
- Static Members: use the static keyword; belongs to the class itself rather than an instance
- Interface implementation: use the implements keyword to implement an interface
- abstract classes: use the abstract keyword; cannot be instantiated and serves as a base class
Classes are the foundation of object-oriented programming in TypeScript; using them appropriately can make code more structured and maintainable.