In TypeScript, there is a curious phenomenon where private properties seem to be mimicking the

Here is an example of an issue I encountered while working with private properties in TypeScript.

I expected that only the public properties would be visible in my object output, similar to normal encapsulation.

My aim here is to include the property with a setter and getter as part of the exposed API of my class rather than the private property (similar to C#).

 class MyClass {
      public otherProp: boolean;

      constructor() {
          this.otherProp = false;
          this._privateProp = false;
      }

      private _privateProp: boolean;

      get publicProp() : boolean {
        return this._privateProp;
      }

      set publicProp(values : boolean) {
          this._privateProp = values;
      }

    }

    let x: MyClass = new MyClass();

    console.log(x); // MyClass {otherProp: false, _privateProp: false}
                   // Expected output: MyClass {otherProp: false, publicProp: false}

Answer №1

To make properties private in TypeScript, you can use the `#` symbol:

class MyClass {
      public otherProp: boolean;

      constructor() {
          this.otherProp = false;
          this.#_privateProp = false;
      }

      #_privateProp: boolean;

      get publicProp() : boolean {
        return this.#_privateProp;
      }

      set publicProp(values : boolean) {
          this.#_privateProp = values;
      }

    }

    let newObj: MyClass = new MyClass();

    console.log(newObj); // MyClass {otherProp: false}

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

Leveraging Underscore in ReactJS applications

I'm encountering an issue with integrating Underscore into my ReactJS project. When I attempt to run my ReactJS class, the following error arises: Uncaught ReferenceError: _ is not defined index.html <html> <head> <meta http-equi ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Combine two sets of JavaScript objects based on their positions using Underscore.js

Data Set 1: {id: "01", name: "John Doe", age: "25", city: "New York", country: "USA"} Data Set 2: [{key:'id', value:'01'},{key:'name', value:'John Doe'},{key:'age', value:'25'},{key:'city& ...

Send an ajax request to upload several images to the server

I am currently facing an issue with my web application that allows users to create posts with a maximum of 15 images. I have implemented AJAX requests to send all the data, including the images, in one request. However, I encountered this error: An error ...

Automate Zoom join function with the help of puppeteer

Having trouble joining a Zoom meeting using Puppeteer, my code is not capturing the password field. Can anyone assist? Here is my code snippet: const puppeteer = require("puppeteer-extra"); const StealthPlugin = require("puppeteer-extra-plu ...

Error encountered: The property 'localStorage' is not found on the 'Global' type

Calling all Typescript enthusiasts! I need help with this code snippet: import * as appSettings from 'application-settings'; try { // shim the 'localStorage' API with application settings module global.localStorage = { ...

There is a SyntaxError due to an unexpected token "o" in the JSON data. It is not a valid JSON format

This code is designed to check an XML file to see if the email or login inputted by a user is already in use, and then provide a JSON response. The AJAX code for this functionality is as follows: $.ajax({ type: 'post', dat ...

The state of dynamically created Angular components is not being preserved

My current task involves dynamically creating multiple components to be placed in a table. The code successfully achieves this objective, but the state seems to be getting jumbled up at the level of the dynamically generated components. When a component is ...

What is the process of creating a download link for a server file in a web browser?

I am attempting to create a straightforward download link for a PDF file that users can upload and then have the option to download. I would like this download feature to appear either in a pop-up box or simply on the Chrome download bar. Despite trying v ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

Developing a project using npm and Node.js with Typescript has been smooth sailing so far. However, an issue has arisen

Recently, I came across a helpful guide on setting up a Node.js project in Typescript on this website: https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html The guide also provides instructions for auto-recompilation upon changes when using npm st ...

Issue: Failed to locate module @angular/core

When attempting to run an Angular 4 application, I consistently encounter the following error: ERROR in Could not resolve module @angular/core There are no additional errors present. There are no dependency issues whatsoever as @angular/core is located i ...

The problem arises when Angular's $interval function is not recognized

Despite the possibility of this being considered a duplicate, none of the related topics have provided a solution to my simple date count down directive: class Clock { constructor() { this.restrict = 'AC'; this.replace = true ...

Inexperienced individual asks: 'Is it possible to accomplish this task using Dojo and Ajax?'

On my website, there is a feature that sends an initial request to a web service. Once this request is sent, the user has to wait for a specific amount of time before being able to send a second request. During this waiting period, I would like a countdo ...

What is the process for sending a post request with a JSON payload to an external API using Node.js?

I am currently facing an issue while attempting to send a POST request with a JSON payload to an external API using node.js. Below is the code I am using: var express = require('express'); var bodyParser = require('body-parser'); var ...

Is there a way to specifically target the MUI paper component within the select style without relying on the SX props?

I have been experimenting with styling the Select MUI component using the styled function. I am looking to create a reusable style and move away from using sx. Despite trying various methods, I am struggling to identify the correct class in order to direct ...

"Encountered an error: 'Invalid private class xy' in the process of constructing an Angular library

Currently, I am in the process of creating an npm package using Angular. In the midst of building the library, I encountered the following error: An unexpected issue with the private class MyLibComponent has surfaced. While this class is accessible to us ...

Issues with the initial calculator project I built using JavaScript (excluding HTML and CSS)

My first calculator is nearly complete, but I have encountered a challenge. The functionality of my calculator is quite simple; it prompts the user for input using window.prompt and performs addition, subtraction, multiplication, or division based on the u ...

What is the best way to ascertain the variance between two Immutable.js Maps?

I currently have two unchangeable maps: const initial_map = Map({x: 10, y: 20)} const updated_map = Map({x: 15, y: 20)} Can anyone advise on how to find the changes between the two maps? The expected outcome should be: Map({x: 15}) ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...