I'm currently using TypeScript and trying to figure out how to implement an interface in a class that utilizes ES6 getters and setters.
Is it even possible? When I use the code below, errors are highlighted in the class.
For instance:
(property) SportsCar.make: string
Property 'make' in type 'SportsCar' cannot be assigned to the same property in base type 'Car'.
Type 'string' is not assignable to type '{ (make: string): string; (): void; }'.ts(2416)*
The following is the code in question:
export interface Car {
_make: string;
_model: string;
make(make: string): string; // for setter
make(): void; // for getter
model(model: string): string; // for setter
model(): void; // for getter
}
class SportsCar implements Car {
_make: string;
_model: string;
constructor(make:string, model: string) {
}
set make(make: string) {
this._make = make
}
get make() {
return this._make
}
set model(model: string) {
this._model = model
}
get model() {
return this._model
}
}
module.exports = SportsCar;
Using getMake()
and setMake()
instead of ES6 getters and setters does work. However, my preference is to utilize ES6 class getters and setters if feasible.
For example, the following setup functions correctly:
export interface Car {
_make: string;
_model: string;
setmake(make: string): void; // for setter
getmake(): string; // for getter
setmodel(model: string): void; // for setter
getmodel(): string; // for getter
}
class SportsCar implements Car {
_make: string;
_model: string;
constructor(make:string, model: string) {
}
setmake(make: string) {
this._make = make
}
getmake() {
return this._make
}
setmodel(model: string) {
this._model = model
}
getmodel() {
return this._model
}
}
module.exports = SportsCar;
Lastly, when working with an interface, is there a way to set class properties to private? It seems interfaces do not provide an option to define privacy. If I attempt to do so as seen in the code snippet below, VS Code throws an error.
This is the code block causing the issue:
export interface Car {
_make: string;
_model: string;
setmake(make: string): void; // for setter
getmake(): string; // for getter
setmodel(model: string): void; // for setter
getmodel(): string; // for getter
}
class SportsCar implements Car {
private _make: string;
private _model: string;
constructor(make:string, model: string) {
}
setmake(make: string) {
this._make = make
}
getmake() {
return this._make
}
setmodel(model: string) {
this._model = model
}
getmodel() {
return this._model
}
}
module.exports = SportsCar;
Error Encountered:
class SportsCar Class 'SportsCar' incorrectly implements interface 'Car'. Property '_make' is private in type 'SportsCar' but not in type 'Car'.ts(2420)