TypeScript - Klassen und Interfaces

in #deutschlast year

Im letzten Beispiel hatten wir ein Object 'point2D' angelegt. Das Problem mit nativen objects ist, wenn man ein Array damit erstellen möchte, so ist der Arraytyp 'any' und nicht 'point2D'. Hier möchte ich dieses 'point2D' als Klasse schreiben und es durch ein Interface erweitern. Mit einer Klasse können wir ein 'point2D-Array' erstellen. Das Interface stellt sicher, dass die angegebenen Variablen und Funktionen in der Klasse implementiert werden müssen. Ansonsten gibt es eine Fehlermeldung.
Für dieses Beispiel ist die Verwendung eines Interfaces überflüssig, aber für Demonstrationszwecke okay.

// interfaces declares something but it does not implement the logic
interface IPoint {
    x : number,
    y : number,
    printCoords : Function
}

// classes are a blueprint. Instances can be created
class Point2D implements IPoint {
    public x : number;
    public y : number;

    constructor(x : number, y : number) {
        this.x = x;
        this.y = y;
    }

    public getCoords() : number[] {
        return [this.x,this.y];
    }

    public printCoords() : void {
        console.log(`${this.x} ${this.y}`);
    }
}

let points : Point2D[] = [];
points.push(new Point2D(3,5));
points.push(new Point2D(4,6));
points.forEach(elem => elem.printCoords());

Coin Marketplace

STEEM 0.26
TRX 0.13
JST 0.031
BTC 61372.29
ETH 2888.95
USDT 1.00
SBD 3.62