Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typescript手册-类与接口 #24

Open
Pasoul opened this issue Mar 19, 2019 · 1 comment
Open

typescript手册-类与接口 #24

Pasoul opened this issue Mar 19, 2019 · 1 comment

Comments

@Pasoul
Copy link
Owner

Pasoul commented Mar 19, 2019

之前我们总结对象的类型-接口时,了解到接口有两个作用,一个是对对象的形状进行描述,而这一节讲述另一个作用:对类的一部分行为进行抽象

类实现接口

一般来讲,一个类只能继承自另外一个类,有时候不同的类有相同的特性,可以把这些特性单独提取成一个接口(interface),然后用类去实现(implements)它。

比如门Door是一个类,防盗门是门的子类,防盗门有一个报警的方法,这时另一个类Car,也有报警的功能,我们可以把报警这个功能单独提取成一个接口,让防盗门和车都去实现它:

interface Alarm {
  alert();
}
class Door{

}
class SecurityDoor extends Door implements Alarm {
  alert() {
    console.log('SecurityDoor alert');
  }
}
class Car implements Alarm {
  alert() {
    console.log('Car alert');
  }
}

如果Car没有实现接口定义的alert方法,编译将会报错:

class Car implements Alarm {
 
}
 // Class 'Car' incorrectly implements interface 'Alarm'.
 //  Property 'alert' is missing in type 'Car'.

一个类可以实现多个接口:

interface Alarm {
  alert();
}
interface Light {
  lightOn();
  lightOff();
}
class Car implements Alarm,Light {
  alert() {
    console.log('Car alert');
  }
  lightOn(){
    console.log('open light')
  }
  lightOff(){
    console.log('close light')
  }
}
@Pasoul
Copy link
Owner Author

Pasoul commented Mar 19, 2019

接口继承接口

和类一样,接口也可以继承接口,可以让我们将接口拆分成更小的单元进行组合

下面例子我们定义了三个接口,分别描述了对象的三种行为:生蛋、会生蛋会游、会生蛋会飞,因为部分海洋生物和部分飞行生物都具有生蛋的行为,这里我们单独提取到Egg接口,在用HalobiosFlyingCreature继承Egg,很方便的达到重用的目的

interface Egg {
  layEgg();
}
// 定义海洋生物接口
interface Halobios extends Egg {
  swim();
}
// 定义飞行生物接口
interface FlyingCreature extends Egg {
  fly();
}
class Fish implements Halobios {
  layEgg() {}
  swim() {}
}
class Bird implements FlyingCreature {
  layEgg() {}
  fly() {}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant