Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below;

class Point{
  x:number;
  y:number;
  constructor(x,y)
  {
    this.x=x;
    this.y=y;
  }
}

const a = { first: new Point(8,9), second: new Point(10,12) };
let someBool = true;

function modifyProperty(a) {
  let c = someBool? a.first: a.second;

  let newPoint = new Point(0,0);
  c = newPoint;         // Doesn't work

  someBool = !someBool;
}

modifyProperty(a);
console.log(a.first);

In this scenario, alternating between modifying 'a' properties when calling modifyProperty() doesn't quite work as expected.

One possible solution involves making the properties in 'a' objects themselves. Essentially like so:

 const a = { first: {value: new Point(8,9)}, second: {value: new Point(10,12)} };

This allows you to assign a new value to 'c' using c.value = newPoint. However, this workaround is not ideal given that it would need to be done for each property within an object.

Is there a better way to achieve pass-by-reference for accessing these properties? While JavaScript only supports this for objects and arrays, what about instances of classes?

Noting how Babel treats classes as functions in standard Javascript conversion, could utilizing their object callable nature provide a potential solution?

Answer №1

Nevertheless, whenever I allocate 'c' to either 'a.first' or 'a.second', it simply passes by value

Absolutely, when you assign a value in JavaScript or TypeScript, it always changes the value on the left side of the equal sign (=). Unfortunately, there is no way to change this behavior.

An alternative approach is to utilize the property name along with the object to which the property belongs rather than using a reference:

type Pair<T> = { first: T, second: T }

function modifyProperty(a: Pair<Point>) {
    let c: keyof Pair<Point> = someBool? 'first' : 'second'; 
    // The keyof Pair<Point> type annotation ensures that only property names from Pair can be assigned to c  

    let newPoint = new Point(0,0);
    a[c] = newPoint;         

    someBool = !someBool;
}

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

What is the best way to eliminate the border on Material UI's DatePicker component?

Check out this code snippet for implementing a datepicker component: import React, { Fragment, useState } from "react"; import { KeyboardDatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers"; import DateFnsUtils from &qu ...

In order to ensure JavaScript can be universally applied to all images, it needs to be made more generic

I have developed JavaScript functions to enable zoom in and zoom out functionality for an image through pinching gestures. Now, I aim to refactor the code below so that I can include it in a shared JavaScript file. var scale = 1; var newScale; ...

Utilizing the power of jQuery's $.each method to dynamically generate HTML select options within an AJAX

I am working with a bootstrap modal that includes a form which requires data from the database. To retrieve this data, I am using PHP as shown below: public function get_view_for_inspection_report_belum_eor(){ $q = $this->inspection->get_view_fo ...

Having trouble with form validation in React.js? Wondering about the best ways to compare two fields? Let's

It's important to ensure that users enter the same email in both the email and confirmEmail input fields. I've experimented with a few methods, but I'm not certain of the best approach. Is there a simpler way that I might be overlooking? In ...

Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results. Initially, the following approach worked well: const value = 'TTest90()'; const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2 ...

Properly aligning text with checkboxes using HTML/CSS and tags like <span> or <div>

My goal is to have the text displayed as a block in alignment with the checkbox, adjusting based on the sidebar's width. For reference: Current Layout Preferred Layout I have shared the code on CodePen (taking into account screen resolution and wi ...

Having difficulties incorporating a separate library into an Angular project

My typescript library contains the following code, inspired by this singleton example code export class CodeLib { private static _instance: CodeLib; constructor() { } static get instance(): CodeLib { if(!this._instance){ ...

What factors contribute to TypeScript having varying generic function inference behaviors between arrow functions and regular functions?

Consider the TypeScript example below: function test<T = unknown>(options: { a: (c: T) => void, b: () => T }) {} test({ a: (c) => { c }, // c is number b: () => 123 }) test({ b: () => 123, a: (c) => { retur ...

What could be causing the video not to display in landscape mode on the iPad Pro?

I'm having an issue with a standard HTML5 <video> on my website. The videos are working fine on most devices, however there is a problem specifically with the iPad Pro in landscape orientation. It seems to work properly in portrait orientation ...

Tips for including a hashtag in an AJAX request

When using ajax to send messages to the server in my chat application, I encountered an issue where everything after a hashtag is omitted. I attempted to address this by encoding the message, but it resulted in other complications in the PHP code. The enco ...

Are you initiating several Ajax requests simultaneously?

What is the best approach to updating multiple sections of a page using Ajax? I am working with two divs and two PHP files. My goal is to use jQuery Ajax to populate one div with data received from one PHP file and the other div with data from the second ...

What is the best way to detect a specific button press from an external component?

I need to integrate an external component written in Vue.js that contains multiple buttons. How can I specifically target and capture the click event of a particular button called firstButtonClick() within this external component? Here is how the External ...

What happens if you try to add a member to a Mailchimp list who is already on the list

After following Angela Yu's course for the past few weeks, I attempted to implement the Mailchimp API as she demonstrates. However, I encountered difficulties due to recent changes in Mailchimp. Despite this setback, I was able to find the API referen ...

Visual traceroute, like the one on "yougetsignal.com", provides a way to update a div element either on demand or periodically

This is my very first question on a forum, yay! I will do my best to ask clearly and concisely. I am currently working on creating a visual traceroute similar to the one found on yougetsignal.com by Kirk Ouimet. My project is up and running using bash co ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

When the user clicks on the page, show the data fetched from MySQL and echoed in

I am facing an issue with a table containing a loan_id. When fetching the information, everything appears to be in order. However, I need to be able to click on the loan_id number and have it display results based on the corresponding id number. <?php ...

Magnify novice mistakes: Unhandled promise rejection and Ensure every child has a distinct "key" property

Currently, I am working through Amazon's Getting Started with AWS tutorial found here: https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-four/ After successfully building and hosting the app on git, I noticed that ...

I'm having trouble understanding how to utilize startAt and endAt in Firebase version 9

Trying to implement geo querying in my firestore db with the new version of firebase has been challenging. The code examples provided in the documentation reference an older version, making it difficult for me to understand how to use ".startAt" and ".endA ...

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...