1. 类与接口
接口(Interfaces)可以用于对【对象的形状(Shape)】进行描述。
2. 类实现接口
interface Alarm {alert(): void;}interface Light {lightOn(): void;lightOff(): void;}class Door {public get material(): string {return this.material;}public set material(v: string) {this.material = v;}}class SecurityDoor extends Door implements Alarm {alert(): void {console.log("Method not implemented.");}}class Car implements Alarm , Light {lightOn(): void {throw new Error("Method not implemented.");}lightOff(): void {throw new Error("Method not implemented.");}alert(): void {throw new Error("Method not implemented.");}}
3. 接口继承接口
class Car implements Alarm , Light {lightOn(): void {throw new Error("Method not implemented.");}lightOff(): void {throw new Error("Method not implemented.");}alert(): void {throw new Error("Method not implemented.");}}
4. 接口继承类
class Point {/**静态方法 */static origin = new Point(0, 0);/*** 静态方法,计算与原点的距离*/static distance(p2: Point, p1: Point = this.origin) {return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y));}x: number;y: number;constructor(x: number, y: number) {this.x = x;this.y = y;}print() {console.log('x:' + this.x, 'y:' + this.y);}}interface Point3D extends Point {z: number;print();}let point3D: Point3D = { x: 1, y: 2, z: 3 , print}console.log('point3D: ' + point3D)
