Languages
[Edit]
EN

TypeScript - interface getter

17 points
Created by:
Richard-Bevan
413

In this article, we would like to show how in TypeScript create getter in interface and later implement it.

W TypeScript nie jest możliwe dodawanie getterów bezpośrednio do interfejsu. W interfejsie można określić tylko właściwość tylko do odczytu.

Quick solution:

interface Interface {
    readonly getter: string;
}

class Implementation implements Interface {
    get getter(): string {
        return 'Some value here ...';
    }
}

 

Practical 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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join