以下是 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);
}
}