Languages
[Edit]
EN

TypeScript - interface getter

14 points
Created by:
Marcin
15710

In TypeScript does not allow to add getters directly to interface.Ā It is possible to specyfy only property in interface that can be implemenetedĀ asĀ getterĀ in following way.

Interface getter example

interface Square {
    readonly name: string;

    readonly x: number;
    readonly y: number;
}

class LocalSquare implements Square {

    public constructor(private _name: string, 
        private _x: number = 0, private _y: number = 0) {
        // nothing here...
    }

    get name() : string {
        return this._name;
    }

    get x(): number {
        return this._x;
    }

    get y(): number {
        return this._y;
    }
}

let a = new LocalSquare('A', 1, 2);

console.log(`${a.name}(${a.x}, ${a.y})`);

Complilation and running:

$ tsc --target ES5 Script.ts
$ node Script.js

Output:

A(1, 2)

Run it online here.Ā 

Notes:

  • to enable getters supportĀ --targer ES5Ā parameter during complilation is necessary (check full list of targets here)
  • readonly keyword in interface is optional

References

  1. Readonly properties - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
šŸš€
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

ā¤ļøšŸ’» šŸ™‚

Join