extends 和 implements

以下是 extends 和 implements 在ts中的区别和示例:

示例1:使用 extends 实现类继承

class Animal {
  move() {
    console.log('Moving');
  }
}

class Dog extends Animal {
  bark() {
    console.log('Barking');
  }
}

const dog = new Dog();
dog.move();  // 继承自父类 Animal 的方法
dog.bark();  

使用 extends 实现接口的扩展

interface BaseInterface {
  name: string;
}

interface ExtendedInterface extends BaseInterface {
  age: number;
}

const obj: ExtendedInterface = {
  name: 'John',
  age: 30
};

 使用 extends 实现继承和重写方法

class Parent {
  showMessage() {
    console.log('Parent message');
  }
}

class Child extends Parent {
  showMessage() {
    console.log('Child message');
  }
}

const child = new Child();
child.showMessage();  // 输出 'Child message'

使用 extends 实现继承构造函数和属性

class Parent {
  constructor(public name: string) {}
}

class Child extends Parent {
  constructor(name: string, public age: number) {
    super(name);
  }
}

const child = new Child('Alice', 10);
console.log(child.name);  // Alice
console.log(child.age);  // 10

示例2:使用 implements 实现接口   class  classA implements interfaceA 

在 TypeScript 中,implements 关键字用于类实现接口。

接口定义了一组方法和属性的签名,而使用 implements 关键字的类必须提供与接口定义相匹配的实现。

以下是一些常见的使用场景:

1.定义公共契约
               当多个类需要遵循相同的一组规则或行为时,可以创建一个接口来定义这些规则。然后,让相关的类使用 implements 来实现这个接口,确保它们具有一致的公共方法和属性。

interface IPrintable {
  print(): void;
}

class Document implements IPrintable {
  print(): void {
    console.log('Printing document');
  }
}

class Image implements IPrintable {
  print(): void {
    console.log('Printing image');
  }
}

2.模拟多重继承
        在 TypeScript 中不支持类的多重继承,但可以通过接口和 implements 来实现类似的效果。

interface IReadable {
  read(): void;
}

interface IWriteable {
  write(): void;
}

class File implements IReadable, IWriteable {
  read(): void {
    console.log('Reading file');
  }

  write(): void {
    console.log('Writing to file');
  }
}

interface Comparer<T> {
  compare(a: T, b: T): number;
}

class StringComparer implements Comparer<string> {
  compare(a: string, b: string) {
    // 比较字符串的逻辑
    return a.localeCompare(b);
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天吃饭的羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值