TypeScript- primary classes and interfaces -06-

Classes and interfaces

Before learning too , Interface (Interfaces) can be used to "shape (Shape) object" to describe.

This chapter introduces another use interface behavior on the part of the class abstract.

Class implements the interface

Implement (implements) is an important concept in object-oriented. In general, a class can only inherit from another class, you can have some common characteristics between different classes sometimes, this time you can put into a feature extraction interfaces (interfaces), use implementsthe keyword to achieve. This feature greatly increases the flexibility of object-oriented.

For example, a class is the door, the door security door subclass. If there is a security door alarm function, we can simply add a method to the security door alarm. This time if there is another class, car, there are alarm function, you can consider the alarm extracted, as an interface, security doors and cars are to achieve it:

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');
    }
}

A class can implement multiple interfaces:

interface Alarm {
    alert();
}

interface Light {
    lightOn();
    lightOff();
}

class Car implements Alarm, Light {
    alert() {
        console.log('Car alert');
    }
    lightOn() {
        console.log('Car light on');
    }
    lightOff() {
        console.log('Car light off');
    }
}

In the embodiment, Carimplements Alarmand Lightinterfaces, both alarms can switch lights.

Interface interface inheritance

Between the interface and the interface can be inheritance:

interface Alarm {
    alert();
}

interface LightableAlarm extends Alarm {
    lightOn();
    lightOff();
}

The above example, we use extendsthe LightableAlarminheritance Alarm.

Interface inheritance class

The interface can also be inherited class:

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};

Mixed types

Function definition interface, the interface may be used to define the way a function of the shape required to comply with:

interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    return source.search(subString) !== -1;
}

Sometimes, a function can also have its own properties and methods:

interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function (start: number) { };
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;

Guess you like

Origin www.cnblogs.com/idspring/p/11784737.html