TypeScript 中的 implements 和 extends

本文探讨了TypeScript中的类和接口的概念。通过示例代码展示了类如何同时作为类型使用,以及接口如何继承类。同时解释了`extends`和`implements`关键字在类与接口之间的关系,说明了在TypeScript中类可以继承类,接口可以继承接口或类,类也可以实现接口或类。强调了在接口继承类时,并没有本质区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类和接口

关于类

在理解类和接口的关系之前,先看一段代码:

class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};

上述代码在声明 class Point 时,除了会创建一个名为 Point 的类之外,同时也创建了一个名为 Point 的类型(实例的类型)。

所以既可以将 Point 当做一个类来用, 也可以将 Point 当做一个类型来用

class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

//作为类使用
const p = new Point(1, 2); 

//作为类型使用
function printPoint(p: Point) {
    console.log(p.x, p.y);
}
printPoint(new Point(1, 2));

这个例子等价于:

class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

// TS偷偷做的事情 ----
interface PointInstanceType {
    x: number;
    y: number;
}
// ------/

//作为类使用
const p = new Point(1, 2); 

//作为类型使用
function printPoint(p: PointInstanceType ) {
    console.log(p.x, p.y);
}
printPoint(new Point(1, 2));

换句话说,「接口继承类」和「接口继承接口」没有什么本质的区别。

extends(继承)和 implements(实现)

因为类可以作为接口使用,或者说因为类同时实现了接口,所以 TypeScript 中可以有如下关系:

  • 类继承类
  • 接口继承接口/类
  • 类实现接口/类

参考链接

https://ts.xcatliu.com/advanced/class-and-interfaces.html
https://www.cnblogs.com/pangjianxin/p/10901115.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值