1. 类与接口

接口(Interfaces)可以用于对【对象的形状(Shape)】进行描述。

2. 类实现接口

  1. interface Alarm {
  2. alert(): void;
  3. }
  4. interface Light {
  5. lightOn(): void;
  6. lightOff(): void;
  7. }
  8. class Door {
  9. public get material(): string {
  10. return this.material;
  11. }
  12. public set material(v: string) {
  13. this.material = v;
  14. }
  15. }
  16. class SecurityDoor extends Door implements Alarm {
  17. alert(): void {
  18. console.log("Method not implemented.");
  19. }
  20. }
  21. class Car implements Alarm , Light {
  22. lightOn(): void {
  23. throw new Error("Method not implemented.");
  24. }
  25. lightOff(): void {
  26. throw new Error("Method not implemented.");
  27. }
  28. alert(): void {
  29. throw new Error("Method not implemented.");
  30. }
  31. }

3. 接口继承接口

  1. class Car implements Alarm , Light {
  2. lightOn(): void {
  3. throw new Error("Method not implemented.");
  4. }
  5. lightOff(): void {
  6. throw new Error("Method not implemented.");
  7. }
  8. alert(): void {
  9. throw new Error("Method not implemented.");
  10. }
  11. }

4. 接口继承类

  1. class Point {
  2. /**静态方法 */
  3. static origin = new Point(0, 0);
  4. /**
  5. * 静态方法,计算与原点的距离
  6. */
  7. static distance(p2: Point, p1: Point = this.origin) {
  8. return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y));
  9. }
  10. x: number;
  11. y: number;
  12. constructor(x: number, y: number) {
  13. this.x = x;
  14. this.y = y;
  15. }
  16. print() {
  17. console.log('x:' + this.x, 'y:' + this.y);
  18. }
  19. }
  20. interface Point3D extends Point {
  21. z: number;
  22. print();
  23. }
  24. let point3D: Point3D = { x: 1, y: 2, z: 3 , print}
  25. console.log('point3D: ' + point3D)