Creating a class extension without a duplicate constructor (using private parameters)

As I was attempting to improve Angular's ComponetFixture, I discovered a limitation due to the absence of a copying constructor for this class. (Or am I mistaken?)

Imagine we have a class:

class A
{
  constructor(public pub, private priv) { }
}

Now, if I want to create a class BetterA based on class A:

class BetterA extends A
{
  constructor(a: A)
  {
    // super(a);    <----- this is not possible, so maybe...

    // super(a.pub, a.priv)  // ...this could be a better option, but...
  }

  myFunction(a: string) { return a; }
}

Unfortunately, the second parameter is PRIVATE. Thus, I cannot access it.

What can be done in this situation?

I am aware that one solution is to use prototype like this:

A.prototype['myFunction'] = function(a: string) { return a; } // this must be done with function keyword, it's not working with ()=>{} !!! /there are problem with this pointer/

However, it requires writing something like:

console.log(  classAobject['myFunction']("abc")  );

Instead of:

console.log(  classAobject.myFunction("abc")  );

or

Another approach could be through composition:

class B
{
  public a: A; // or constructor(public a: A)
  myFunction(a) { return a; }
}

Yet, it may not seem very elegant.

Is there a better solution available?

Edit #1

I've recently found out that this syntax:

Class.prototype.NewFunction = function() { this.x.y.z = 123 }

is valid, but it results in compiler errors. The code works, but we encounter:

'Property 'TextOf' does not exist on type 'Class'

and when trying to call it like this:

objectOfClass.NewFunction()

it shows:

'Property 'NewFunction' does not exist on type 'Class'

However,

It only works when using the function keyword. When using a lambda expression, strange invisible problems with some functions might occur.

Answer №1

In my opinion, utilizing composition is the ideal approach in this scenario. It's important to keep in mind that you are constructing a class, not a method that necessitates the new operator for object instantiation. This could be the solution you are seeking.

class A {
  tPub;
  constructor(public pub, private priv) {
    this.tPub = pub;
  }
}
class B extends A {
  constructor(pub) {
    super(pub);
  }
  myFunc() {} //equivalent to B.prototype.myFunc
}

export const myClass = new B();

//another file
import { myClass } from './file';
let m = myClass.myFunc();

Regrettably, declaring priv as private will indeed render it a private object as instructed. Depending on your intentions with the class, you could also omit the constructor.

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

Combining Vitest with FastifyAutoload resulted in a FastifyError: The plugin provided must either be a function or a promise, but instead, an 'object' was received

My application built on Fastify ("fastify": "^4.26.0") operates smoothly under normal conditions with no issues. However, when trying to incorporate unit testing using Vitest, every test fails despite their simplicity. Upon troubleshoot ...

By default, the Bootstrap UI Collapse is set to be open

I'm facing an issue with the bootstrap ui collapsed directive. It seems to be showing open by default when I actually need it to be collapsed on page load. I've double-checked my variables and settings, but it still isn't functioning correct ...

Encountering an issue with NextJS 13 when utilizing the vectorstore recommended by Langchain, specifically receiving an error message stating that HNSWLib

Currently, I am building an application utilizing Langchain and OpenAI for assistance. My approach involves loading data using JSONLoader and intending to save it in a vectorstore. This way, I can provide specific answers to user queries based on the store ...

When the imagepath in an Angular application is not updated, it will revert to null

Below is the code snippet that I am currently working on: <div class="col-sm-4 pl-5"> <img attr.src="{{item?.imagePath}}" required height="200" width="200"> </div> In my TypeScript file (ts), I have the following function: editBlog ...

404 Error message encountered across all routes in a Node TypeScript Azure Function App - Resource not located

I keep encountering a 404 Not Found error on all routes while requesting my API. I am struggling to correctly write the code. Here's an example of my code: host.json: { "version": "2.0", "extensions": { & ...

Using AngularJS and Jasmine to tackle challenges in writing spec tests

After setting up my seed and successfully getting Jasmin Running (huge thanks to SoEzPz for the assistance), I encountered an issue with my specs. When I tried to write a spec on a controller, it resulted in errors. However, when running an isolated spec, ...

Steps for retrieving the output of a sequelize query that is enclosed within a function

I am currently in the process of developing a platform that generates a distinct URL for each user. The functionality is as follows: Firstly, I check the database to determine if the user already possesses a URL, and if so, return it. If the user ...

How to ensure that a div element occupies the entire height of the webpage

After developing a small app in Angular, I'm looking to make the container element expand to the full height of the page, even when the content doesn't fill the entire space. On larger screens, the page doesn't stretch as desired. Here' ...

Expanding a TypeScript type by creating an alias for a property

I am working on defining a type that allows its properties to be "aliased" with another name. type TTitle: string; type Data<SomethingHere> = { id: string, title: TTitle, owner: TPerson, } type ExtendedData = Data<{cardTitle: "title&qu ...

Utilizing symbols as a keyof type: A simple guide

Let's consider the following: type Bar = keyof Collection<string> In this scenario, Bar denotes the type of keys present in the Collection object, such as insert or remove: const x: Bar = 'insert'; ✅ But wait, the Collection also c ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

Tips on enabling click function in an ionic infowindow

After creating a div in my HTML file and referencing it in my TS file using document.getElementByID, I utilized its inner HTML as the content for an infowindow. However, despite my efforts, I am unable to get clicks working. Adding event listeners to any e ...

Understanding the moment when the DOM is fully rendered within a controller

I'm currently facing an issue with AngularJS. In my controller, I have a $watch setup like this: function MyController() { $watch('myModel', function() { $rootScope.$emit('do-oper'); }); } The value of 'myMod ...

Creating dynamic image carousels using the latest versions of Bootstrap and AngularJS

I have created an array that stores various images using angularJS: $scope.docImg = [ '../../Content/Image/BackGrounds/abra.png', '../../Content/Image/BackGrounds/background_black.jpg', '../../Content/I ...

Adding attributes to parent DOM elements of a component in Angular2: A Step-by-Step Guide

I'm working with the following code: ... <div class="container"> <div class="fancy"> <fancybutton></fancybutton> </div> <button (click)="addAttribute()">Remove</button> <button (click)="remAttr ...

The parameter in Angular cannot be assigned a type of 'null'

@Injectable({ providedIn: 'root' }) export class AuthenticationService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private http: HttpClient) { this.curren ...

What is the process for declaring global mixins and filters on a Vue class-based TypeScript component?

Recently, I've been working on incorporating a Vue 2 plugin file into my project. The plugin in question is called global-helpers.ts. Let me share with you how I have been using it: import clone from 'lodash/clone' class GlobalHelpers { ...

AngularJS module dependencies configuration functions smoothly during initialization

The structure of my modules looks like this: angular.module('mainModule',["cityModule", "countryModule"]); angular.module('mapModule',[]); angular.module('cityModule',["mapModule"]); angular.module('countryModule',[ ...

Material UI autocomplete is not detecting the options parameter as an array

I am currently working on implementing an autocomplete field that retrieves options from my component's state, which in turn fetches data from the backend. Here is a snippet of my component: export const Person: React.FC<PersonProps> = ({name, a ...

Angular JS Sorting Wordpress Plugin allows users to easily organize and sort content

Seeking some assistance here, any help would be greatly appreciated. Currently using a Wordpress Angular JS plugin that is causing some unusual alphabetical sorting. This snippet of code showcases the taxonomy: <!-- for taxonomy --> <div ng-if ...