Accessing the hidden properties of an object within a class

I encountered the following explanation and found it confusing. The main idea is:

The private access modifier in a constructor automatically assigns the parameter to "this" (such as this.file) and makes its visibility private, allowing code within an instance of Position to access and modify it, but not code outside of it. Instances of Position can access each other's private members, while instances of any other class - even a subclass of Position - cannot.

Could someone please clarify what this actually means? Maybe with an example.

Answer №1

Private members in TypeScript classes are considered class-private, not instance-private. This means that inside the body of a class, you can access private members of other instances of the same class. For example:

class Foo {
    private bar: number;
    constructor(bar: number) { this.bar = bar; }
    lessThan(otherFoo: Foo) {
        return this.bar < otherFoo.bar
        // -------------> ^^^^^^^^^^^^
    }
}
const f0 = new Foo(0);
const f1 = new Foo(1);
console.log(f0.lessThan(f1)) // true
console.log(f1.lessThan(f0)) // false

In the above code snippet, referencing otherFoo.bar is only possible because bar is private to the Foo class.


One implication of this behavior is that outside of a class, you can see that a private member exists but cannot access its value. If you were able to access it, you might run into issues like this:

class Qux {
    private x = "abc";
    y = 123;
    method(otherQux: Qux) { 
      console.log(otherQux.x.toUpperCase()) 
    }
}

const q = new Qux();

q.method({
    y: 123,
    method: Qux.prototype.method
}) // runtime error

In this example, Qux has a private property x and a public property y, along with a method method. Trying to access otherQux.x from outside the class results in a runtime error due to the nature of private members.

Attempting to work around this by adding x to the object also leads to compiler errors, highlighting the restrictions imposed by using private properties.

This limitation enforces nominal typing, where objects must be created through specific class constructors to match the intended type. It contrasts with structural typing, where the shape of an object matters more than its declaration.

Link to Playground for code demonstration

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

Add a new class to the Custom Repository

In my project, I have developed a class called S3Service that handles the task of uploading and deleting objects (such as images) from S3. Since I intend to utilize this "service" in various modules, I decided to create a custom module named UtilsModule wh ...

The functionality of TypeScript's .entries() method is not available for the type 'DOMTokenList'

I'm currently working with a stack that includes Vue3, Vite, and TypeScript. I've encountered an issue related to DOMTokenList where I'm trying to utilize the .entries() method but TypeScript throws an error saying Property 'entries&apo ...

Numerous unspecified generic arguments

Imagine a collection of functions, each capable of taking an argument and returning a value (the specifics don't matter): function convertToNumber(input: string): number { return parseInt(input) } function convertToBoolean(input: number): boolean { ...

What is the best way to integrate ag-grid with Observable in Angular 2?

After conducting extensive research on the Internet, I am still struggling to connect the pieces. My angular2 application utilizes an Observable data source from HTTP and I am attempting to integrate ag-grid. However, all I see is a loading screen instead ...

Why does Typescript's 'await' seem to not wait as expected?

Apologies for the rookie mistake, I am currently transitioning from a C# background to Ionic, which may be causing some confusion on my end. I'm working on retrieving a stored token from Ionic storage but I'm struggling with understanding promise ...

The error message "the property '_env_' is not found on the type 'Window & typeof globalThis - React / Typescript ERROR" indicates that the specified property is not present in the

I encountered an issue while working with React/TypeScript. When I perform this action within the component: <p>API_URL: {window._env_.API_URL}</p> The error message I receive is: property '_env_' does not exist on type 'Window ...

Bringing PNGs and SVGs into React - Error TS2307: Module not found

While attempting to import PNGs/SVGs (or any other image format) into my React project, TypeScript presents the following error: TS2307: Cannot find module '../assets/images/homeHeroImage.svg' or its corresponding type declarations. The frontend ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Advanced Angular2 Services Expansion

I'm looking to enhance an existing angular service (for example, Http). Requirements: The extension of the service should be done through angular's dependency injection It should be possible to extend the service multiple times using a pattern ...

typescript Can you explain the significance of square brackets in an interface?

I came across this code snippet in vue at the following GitHub link declare const RefSymbol: unique symbol export declare const RawSymbol: unique symbol export interface Ref<T = any> { value: T [RefSymbol]: true } Can someone explain what Re ...

``There are problems with parsing JSON data due to the error message indicating the presence of unexpected

I am encountering an issue with displaying values from objects stored as string[] in appwriteDB. When trying to use *ngFor to iterate through the data, I faced difficulties. Despite attempting to convert the orderItems using JSON.parse(), the process faile ...

Updating input values in Angular reactive forms

I have a repeated table row that includes a form. I need to dynamically update the total field based on the price and quantity in my reactive forms setup. Here is the code snippet: <tbody formArrayName="products"> <tr *ngFor="let phone of pro ...

Issue encountered while attempting to run an Angular project using the CLI: "Module not found - Unable to resolve 'AngularProjectPath' in 'AngularProjectPath'"

Just like the title suggests, I'm facing an issue with compiling my angular project. It seems to be having trouble resolving my working directory: Error: Module not found: Error: Can't resolve 'D:\Proyectos\Yesoft\newschool& ...

Utilize Nativescript XML template for code reusability without the need for Angular

After completing my Nativescript application, I was tasked with incorporating the Telerik-UI "RadSideDrawer". Upon reviewing the documentation, I realized that a substantial amount of XML code needs to be implemented on every page. I am utilizing Typescr ...

What is preventing the combination of brand enums in Typescript 3?

Utilizing brand enums for nominal typing in TypeScript 3 has been a challenge for me. The code snippet below demonstrates the issue: export enum WidgetIdBrand {} export type WidgetId = WidgetIdBrand & string; const id:WidgetId = '123' as Wi ...

What is the process for resetting the mat-date-range-input selection on the calendar?

I've encountered a puzzling problem that has me stumped. I'm working with a mat date range picker in Angular Typescript and have run into an issue while trying to clear any selection made through a function. The code snippet below successfully c ...

Integrating d3.js into an Angular 2 project

Trying to incorporate the d3.js library into a MEAN application using angular2. Here are the steps I've taken: npm install d3 tsd install d3 In mypage.ts file (where I intend to show the d3.js graph) // <reference path="../../../typings/d3/d3.d ...

The panning functionality on Android devices within the Firefox browser is currently experiencing issues with both panstart and pan

Currently, I am collaborating on an Angular7 project and utilizing hammerjs version 2.0.1. One of the tasks at hand is to allow panning functionality on a map for mobile devices. After testing on various android devices, I noticed that it performs well on ...

Having trouble with loading background images in Angular 4?

After researching extensively on stack overflow, I am still struggling to resolve this issue. The main problem I am facing is related to adding a background image to the header tag in my code. Unfortunately, no matter what I try, the background image refu ...

What are the reasons behind my decision not to utilize the correct Card component in React Bootstrap?

I am new to using react. I am attempting to utilize the Card component from bootstrap in the following way: import React from "react"; import { Card, Button } from "@material-ui/core"; const PortfolioSection: React.FC = () => { r ...