EN
TypeScript - interface getter
17 points
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:
xxxxxxxxxx
1
interface Interface {
2
readonly getter: string;
3
}
4
5
class Implementation implements Interface {
6
get getter(): string {
7
return 'Some value here ...';
8
}
9
}
xxxxxxxxxx
1
interface Square {
2
readonly name: string;
3
4
readonly x: number;
5
readonly y: number;
6
}
7
8
class LocalSquare implements Square {
9
10
public constructor(private _name: string, private _x: number = 0, private _y: number = 0) {
11
// Nothing here ...
12
}
13
14
get name(): string {
15
return this._name;
16
}
17
18
get x(): number {
19
return this._x;
20
}
21
22
get y(): number {
23
return this._y;
24
}
25
}
26
27
let a = new LocalSquare('A', 1, 2);
28
29
console.log(`${a.name}(${a.x}, ${a.y})`);
Complilation and running:
xxxxxxxxxx
1
$ tsc --target ES5 Script.ts
2
$ node Script.js
Output:
xxxxxxxxxx
1
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