Can ES6 class getters, setters, and private properties be utilized in TypeScript with an interface?

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)

Answer №1

The realm of possibilities is yours to explore. Take a look at this snippet:

export interface Car {
    make: string;
    model: string;
}

export class SportsCar implements Car {

   private _make: string;
   private _model: string;

  constructor(make:string, model: string) {
    this._make = make;
    this._model = model;
  }

  set make(make: string) {
    this._make = make
  }

  get make() {
    return this._make
  }

  set model(model: string) {
    this._model = model
  }

  get model() {
    return this._model
  }

}

Feel free to experiment with it here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing MUI V5 Variants

I'm having trouble customizing the variant options in MUIPaper, and I can't figure out what mistake I'm making. The available types for the component are: variant?: OverridableStringUnion<'elevation' | 'outlined', Pape ...

Experiencing a problem in React JS when trying to render a component?

I encountered an error message while trying to render a component from an object. Type 'FC<Boxprops> | ExoticComponent<{ children?: ReactNode; }>' is not compatible with type 'FC<Boxprops>'. Type 'ExoticComponen ...

What is the best way to retrieve the previous URL in Angular after the current URL has been refreshed or changed

Imagine being on the current URL of http://localhost:4200/#/transactions/overview/5?tab=2 and then navigating to http://localhost:4200/#/deals/detail/ If I refresh the deals/detail page, I want to return to the previous URL which could be something like h ...

Guide on effectively converting a table of tuples to an array of objects utility function (similar to zip) while preventing the merging of all values in typescript version 5.2.2

Almost there, but stuck on the final TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol compiler error. Here's a nifty utility function called rowsToObjects() that many developers have probably come up with at some point, ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...

JavaScript Equivalent to C#'s BinaryReader.ReadString() Function

Currently, I am in the process of translating C# code into JavaScript. While transferring multiple datatypes from this file to matching functionalities found in various JavaScript libraries was relatively smooth, there is one specific function that seems t ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

What are the reasons for discouraging the use of canActivate always returning false?

I've searched extensively to avoid duplicate postings and tried various solutions, but unfortunately, none of them have resolved the issue. My implementation of canActivate to secure a dashboard seems to be working properly, but it's always retu ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

A step-by-step guide to customizing the Material UI Chips delete SVG icon to appear in white color through

Using a Material UI component, I added a custom class to my chip. Attached is a screenshot showing what I mean. Currently, I am attempting to change the color of the cross button to white. After inspecting the element, I discovered that it is an SVG ico ...

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...

What is the best way to mandate the declaration or type of a function in TypeScript?

Let me present my dilemma: I am aiming to create a declaration file containing TypeScript function models. This file will be utilized by various individuals to build their own programs. To achieve this, I have crafted a def.d.ts file with a small example ...

Offering a limited selection of generic type options in TypeScript

Is there a shorthand in TypeScript for specifying only some optional types for generic types? For example, let's say I have a class with optional types: class GenericClass<A extends Type1 = Type1, B extends Type2 = Type2, C extends Type3 = Type3> ...

Building a table with Next.js

I need assistance in displaying users and their metadata in a table on my website. Here is the code snippet I have: const apiKey = process.env.CLERK_SECRET_KEY; if (!apiKey) { console.error('API_KEY not found in environment variables'); proc ...

Insert information into a 3-tiered nested Angular FormArray within interconnected dropdown fields

After trying to retrieve data from an API call to populate a select form field, I encountered difficulties setting the value correctly using a FormArray. This led me to creating a FormArray with 3 nested levels in Angular, taking reference from this examp ...

Can ng-content be utilized within the app-root component?

I have successfully developed an Angular application, and now I am looking to integrate it with a content management system that generates static pages. In order to achieve this, I need to utilize content projection from the main index.html file. The desi ...

Establish a connection between a React variable and state management

In my codebase, I have an external module file named Task.ts. It contains the following: const taskList: Task[] = []; Class Task { ... } export { Task, taskList } The taskList is a list of Task objects that can be modified by the Task class. Now, i ...

The ReactDOM.createPortal modal has been successfully mounted onto the DOM, however, there seems to be no visible content

This project utilizes TypeScript and Next.js. Within it, there is a Modal component: interface ModalProps { onCancelModal: () => void; onAcceptModal: () => void; acceptEnabled: boolean; isLoading?: boolean; title: string; } const Modal: Re ...

Navigating API data conversion on the frontend using Object-Oriented Programming

Currently, I am facing a challenge while developing the frontend of a web application using TypeScript. The dilemma revolves around efficiently converting a data object from an API response into a format suitable for the application. Let's consider r ...

Guide to executing various datasets as parameters for test cases in Cypress using Typescript

I am encountering an issue while trying to run a testcase with multiple data fixtures constructed using an object array in Cypress. The error message states: TS2345: Argument of type '(fixture: { name: string; sValue: string; eValue: string}) => vo ...