TypeScript 中 extends 关键字

基础概念与语法介绍

extends关键字主要用于类、接口和泛型中,分别实现继承扩展约束功能。在类中,它允许一个类继承另一个类的属性和方法;在接口定义中,他用于合并接口,形成一个包含所有指定接口成员的新接口;而在泛型中,extends用于限制类型变量必须符合某种类型结构,增加了泛型的灵活性和类型的安全性。

类的继承

类的继承是面向对象编程的基本特征之一,extends在此发挥了核心作用。通过继承、子类可以复用父类的属性和方法,同时可选择性的覆盖或扩展他们

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

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

  speak(){
    console.log(`${this.name} is Animal`)
  }
}

class Dog extends Animal {
  speak(){
    console.log(`${this.name} Dog`)
  }
}

在这个例子中,Dog类通过extends继承了Animal类,并覆盖了speak方法以提供更具体的实现。

接口的扩展

接口扩展是TypeScript中实现接口复用组合的强大机制。利用extends,可以创建一个接口,它包含一个或多个其他接口所有成员。

基本接口扩展

假设你有两个基本接口,一个描述了动物的一般特征,另一个专门描述了鸟类的特征。

typescript 复制代码
interface Animal {
    name: string;
    age: number;
}

interface Brid extends Animal {
    fly(): void;
    sing(): string;
}

let brid: Brid = {
    name: 'zyj',
    age: 1,
    fly() {
        console.log('fly');
    },
    sing() {
        return 'sing'
    }
}

在这里,Bird接口通过extends关键字扩展了Animal接口,这就意味着一个实现了Brid接口的对象除了需要有flysing方法还必须有nameage属性。

多接口扩展

有时候一个类或接口可能需要符合多个接口的规范。TypeScript支持多重继承,即一个接口可以扩展多个其他接口。

typescript 复制代码
interface Swinmer {
    swim(): void;
}

interface Flyer {
    fly(): void;
}

interface Duck extends Swinmer, Flyer {
    quack(): void;
}

let duck: Duck = {
    swim() {
        console.log('swim')
    },
    fly() {
        console.log('fly')
    },
    quack() {
        console.log('quack')
    },
}

在上面的例子中,Duck接口通过扩展SwimmerFlyer接口,要求实现了Duck的类型还需要有swimfly方法,以及自己的quack方法。

泛型接口与扩展

接口扩展也可以与泛型一起使用,为泛型类型增加更多约束或行为。

typescript 复制代码
interface Loggable<T> {
    log(message: T): void;
}

interface Identifiable<T> {
    id: T;
}

interface User extends Identifiable<number>, Loggable<string> {
    name: string;
    email: string;
}

const user: User = {
    id: 1,
    name: 'zyj',
    email: '123@qq.com',
    log(message: string) {
        console.log(message)
    }
}

在这个例子中,User接口不仅有自己的属性nameemail,还通过扩展Identifiable<number>获得了id属性,并且通过扩展Loggable<string>要求有一个接受字符串参数的log方法。

我是菜逼,大佬勿喷!

相关推荐
烛阴1 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
奔跑的蜗牛ing2 天前
Vue3 + Element Plus 输入框省略号插件:零侵入式全局解决方案
vue.js·typescript·前端工程化
光影少年2 天前
Typescript工具类型
前端·typescript·掘金·金石计划
开心不就得了3 天前
React 状态管理
react.js·typescript
冷冷的菜哥3 天前
react实现无缝轮播组件
前端·react.js·typescript·前端框架·无缝轮播
lypzcgf3 天前
Coze源码分析-资源库-创建知识库-前端源码-核心组件
前端·typescript·react·coze·coze源码分析·ai应用平台·agent开发平台
患得患失9494 天前
【个人项目】【前端实用工具】OpenAPI to TypeScript 转换器
前端·javascript·typescript
万添裁4 天前
ArkAnalyzer源码初步分析I——分析ts项目流程
typescript·arkanalyzer
凡二人5 天前
Flip-js 优雅的处理元素结构变化的动画(解读)
前端·typescript
烛阴5 天前
【TS 设计模式完全指南】TypeScript 装饰器模式的优雅之道
javascript·设计模式·typescript