TypeScript 类

1. 基本用法

在 TypeScript 中,可以使用 class 关键字来定义类,然后通过 new 关键字来创建类的实例。例如:

typescript 复制代码
class Person {
    name: string;
    age: number;

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

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

let person = new Person("Alice", 30);
person.greet(); // 输出:Hello, my name is Alice and I'm 30 years old.

2. 继承与多态

在 TypeScript 中,类支持继承,子类可以继承父类的属性和方法,并且可以重写父类的方法实现多态。例如:

typescript 复制代码
class Animal {
    name: string;

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

    makeSound() {
        console.log("Animal makes a sound.");
    }
}

class Dog extends Animal {
    makeSound() {
        console.log("Dog barks.");
    }
}

let dog = new Dog("Buddy");
dog.makeSound(); // 输出:Dog barks.

3. 访问修饰符

TypeScript 提供了访问修饰符(Access Modifiers),用于控制类的成员的可访问性。包括 publicprivateprotected。例如:

typescript 复制代码
class Car {
    private speed: number;

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

    accelerate() {
        this.speed += 10;
    }

    getSpeed() {
        return this.speed;
    }
}

let car = new Car(50);
// console.log(car.speed); // Error: 'speed' is private and can only be accessed within class 'Car'
console.log(car.getSpeed()); // 输出:50
car.accelerate();
console.log(car.getSpeed()); // 输出:60

4. 抽象类

抽象类(Abstract Class)是不能直接实例化的类,它只能被继承,用于提供其他类的通用功能。抽象类可以包含抽象方法,子类必须实现这些抽象方法。例如:

typescript 复制代码
abstract class Shape {
    abstract area(): number;
}

class Circle extends Shape {
    radius: number;

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

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

let circle = new Circle(5);
console.log(circle.area()); // 输出:78.53981633974483

5. 类与接口

类与接口是 TypeScript 中两个重要的概念,可以结合使用,实现更灵活的代码结构。例如:

typescript 复制代码
interface Printable {
    print(): void;
}

class Document implements Printable {
    print() {
        console.log("Document is being printed.");
    }
}
相关推荐
把csdn当日记本的菜鸡36 分钟前
js查缺补漏
开发语言·javascript·ecmascript
zhangyao9403301 小时前
uni-app scroll-view特定情况下运用
前端·javascript·uni-app
鎏金铁匠1 小时前
跟着ECMAScript 规范,手写数组方法之map
javascript
daqinzl2 小时前
Ubuntu 使用 Python 启动 HTTP 服务
python·ubuntu·http server 服务
HIT_Weston2 小时前
30、【Ubuntu】【远程开发】内网穿透:反向隧道建立(二)
linux·运维·ubuntu
不爱吃糖的程序媛3 小时前
Electron 智能文件分析器开发实战适配鸿蒙
前端·javascript·electron
flashlight_hi3 小时前
LeetCode 分类刷题:3217. 从链表中移除在数组中存在的节点
javascript·数据结构·leetcode·链表
Java追光着3 小时前
React Native 自建 JS Bundle OTA 更新系统:从零到一的完整实现与踩坑记录
javascript·react native·react.js
努力往上爬de蜗牛3 小时前
react native 运行问题和调试 --持续更新
javascript·react native·react.js
eason_fan4 小时前
Monorepo性能噩梦:一行配置解决VSCode卡顿与TS类型崩溃
前端·typescript·visual studio code