Using TypeScript to implement getter/setter functionality on an array property

Is there a better approach for implementing getter/setter pattern with array properties?

For instance:

export class User {

  private _name: string;

  set name(value: string) {
    this._name = value;
  }

  get name(): string {
    return this._name;
  }

  private _roles = new Array<string>();

  set roles(value: Array<string>) {
    this._roles = value;
  }

  get roles(): Array<string> {
    return this._roles;
  }

  constructor() {
  }
}

Changing user.name triggers the setter method, but modifying items in roles does not.

I believe the reason it doesn't trigger the setter is because adding items to the array doesn't change the pointer, but simply appends to the existing space (please correct me if I'm mistaken).

How can we achieve the desired behavior with getter/setter on array properties?

Answer №1

Instead of directly manipulating the array with user.roles.push('my-role'), consider creating methods like addRole and removeRole. This way, you can control the logic for adding or removing roles from the array while keeping it private.

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

How can I determine which dist folder is utilized during the building of my App if an npm package contains multiple dist folders?

I have integrated an npm package called aurelia-google-maps into my application. This package includes various distribution folders such as AMD, System, CommonJS, Native Modules, and ES2015 within the /node_modules/ directory like so: /node_modules/ /a ...

Unable to pass inherited props from parent to class container in a React Redux TypeScript project

In my code, I create a component class and connect it as shown below: export class SkypeConversationArea extends React.Component<Props> {...} const mapStateToProps = (state: State) => { return { loading: state.loading, hangUp: state.con ...

When the value is empty, MUI Autocomplete will highlight all items

I have encountered a specific issue. I am working on developing a custom Autocomplete Component for filtering purposes. However, I recently came across the following Warning. MUI: The value provided to Autocomplete is invalid. None of the options matc ...

Ways to retrieve a particular element within an array

I am looking to access each individual element of the "to" value within the children property of my array. const items = [{ name: 'Administrator', children: [ { name: 'Catalog', to: 'catalog' }, and he ...

Turn off the button and add a CSS class to it when sending a message

I have an Angular 7 component with a form that includes the following TypeScript code: export class MessageComponent implements OnInit { message: FormGroup; constructor(private formBuilder: FormBuilder, private messageService: MessageService) { } ...

Having trouble adjusting the appearance of the dropdown menu in Angular Material's Select component

I've been attempting to adjust the style of the overlay panel within an Angular Material's MdSelect component in order to change the default max-width property of 280px. I have tried various methods, such as using '!important' to overr ...

What is the best way to transform a delimited string into a multidimensional array with associative keys?

I'm seeking assistance with creating a regular expression, can anyone help me please? For the task at hand, I have a sample string that needs to be converted into a PHP array. $str="hopOptions:hops hopOptions:salmonSafe region:domestic region:specia ...

Converting a frequency distribution table into raw data using MATLAB

I need help converting a 2-column matrix back into raw data. The first column contains events represented as integers, while the second column counts the frequency of those events. I want to reverse the process of tabulate() and transform [0 4; 1 2; 2 2; ...

Error in TypeScript on SendGrid API: Invalid HttpMethod

Here is my code snippet: import sendgridClient from '@sendgrid/client' sendgridClient.setApiKey(process.env.SENDGRID_API_KEY); const sendgridRequest = { method: 'PUT', url: '/v3/marketing/contacts', bo ...

Tips for implementing a decorator in a TypeScript-dependent Node module with Create-React-App

I am working on a project using TypeScript and React, which has a dependency on another local TypeScript based project. Here are the configurations: tsconfig.json of the React project: "compilerOptions": { "target": "esnext& ...

Issues with Angular's router outlet link functionality not performing as expected

I am encountering difficulties trying to create a link to a named router outlet in Angular. Let's focus on the most crucial part of the code: app-routing-module.ts: import { NgModule } from '@angular/core'; import { RouterModule, Routes } ...

Using the arrayfun function in Matlab, we can work with two matrices X and Y that are part of a

Consider matrices X and Y that hold coordinates within specific intervals xc = 0, yc = 0 xl = linspace(xc - 10, xc + 10, 2); yl = linspace(yc - 10, yc + 10, 2); [X,Y] = meshgrid(xl,yl); Let fun be a handle to a function named test(v) fun = @(v)test(v); ...

Utilizing the power of Typescript in Express 4.x

I'm currently working on building an express app using TypeScript and here is what my code looks like at the moment: //<reference path="./server/types/node.d.ts"/> //<reference path="./server/types/express.d.ts"/> import express = requir ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

Utilizing SequelizeJS to Pass an Array of Values

I am currently exploring the possibility of passing an array as the value for the property of an instance. In my model, I have set the dataType to STRING and I am inserting values from jQuery fields into an array which I then parse from the body and assign ...

Error: Attempting to access the 'location' property of an undefined variable is not allowed when using res.redirect

Here is a function that retrieves an object from a database and extracts a URL: async fetchUrl(id: string, redirectFunction: Function) { if (!IdExists(id)) { throw new Error(`ID ${id} does not exist.`); } const redirectLocation: string = ...

Output JSON in PHP with key-value pair

Why is this code not functioning as expected? What mistake have I made? $json = json_encode($myInstance->getData($id)); $result = json_decode($json,true); $i = 0; foreach ($result as $value) { echo '<div>'.$value[$i] ...

How can you vertically center an icon button in Material UI?

Looking for help with aligning elements in this code snippet: <TextField id="outlined-basic" label="22Keyword" defaultValue={"test123"} variant="outlined" /> <IconButton aria-label="delete&q ...

JavaScript: Find the differences among three separate arrays

Looking to compare and combine multiple arrays that may have identical elements: X = [1,2,3]; Y = [1,2,3]; Z = [1,2,3]; M = [10,11,12]; N = [10,11,12]; O = [10,11,12]; P = [13,14]; Q = [13,14]; If there are identical arrays, the goal is to form new arr ...

The 'string[]' type cannot be assigned to the 'string | ParsedUrlQueryInput | null | undefined' type in Next.js and Typescript

I'm facing an issue while attempting to transfer an array of strings from one page to another in Next.js using <Link href={{ pathname: "/model", query: data }}>. The problem arises when the query parameter is red underlined: Type &apos ...