Exploring Mixed Type Arrays Initialization in Typescript using Class-Transformer Library

In my class, I have a property member that is of type array. Each item in the array can be of various types such as MetaViewDatalinked or MetaViewContainer, as shown below

class MetaViewContainer{
      children: (MetaViewDatalinked | MetaViewContainer)[];
}

class MetaViewDatalinked{
     id: string;
}

I am looking to initialize the class with its properties using class-transformer (

plainToClass(MetaViewContainer, json)
).

If my class did not have an array property, like in the example below, I would use @Type

class MetaViewContainer{
          @Type((typeHelpOptions: TypeHelpOptions) => {
               if (typeHelpOptions.object.container)
                   return MetaViewContainer;
               return MetaViewDatalinked;
           })
          child: MetaViewDatalinked | MetaViewContainer;
    }

The problem arises when using @Type because it is called only once irrespective of whether the property is a single class or an array of classes, resulting in an array of one type (in case of an array property).

If you have any suggestions on how to resolve this issue, I would greatly appreciate it.

Answer №1

The problem was resolved by utilizing the @Transform decorator

class MetaViewContainer{
            @Transform((params: TransformFnParams) => {
                 const children: (MetaViewDatalinked | MetaViewContainer)[] = [];
                 if (!params.value) return children;
                 if (Array.isArray(params.value)) {
                    for (const item of params.value) {
                        if (item.children)
                          children.push(plainToClass(MetaViewContainer, item));
                        else
                          children.push(plainToClass(MetaViewDatalinked, item));
                     }
                  }        
                  return children;
          })
          children: (MetaViewDatalinked | MetaViewContainer)[];
    }

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

Guide to finding the index of certain values within a list using Python

Let's say we have a list: A = [1,1,1,0,0,1,0] What is the most efficient way to find and return the index of any occurrence of the number 1 in the list? For this particular example, how can we achieve the following result: [0, 1, 2, 5] This output ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

The onClick event handler is executed during every rendering process

Initially, my default state is set as follows: this.state = { selectedTab : 'tab1' } When it comes to rendering, this is how I define it: render(){ const { selectedTab } = this.state; return( <li>tab1</li><li>ta ...

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

Using Javascript to refresh an image and update a class within a DIV when another DIV is clicked

I have a code that is quite lengthy to share here, so I've created a demo on JSFiddle: http://jsfiddle.net/Emily92/5b72k225/ This particular code takes a random image and divides it into multiple sections based on the class applied to the div contain ...

Verify if two items possess identical property values

There are 2 items: 1. obj1 = { bookRetail: 14.99, hierarchyDescription: "GUYS DENIM PANTS [ 0151 ]", isSelected: true, isAvailableInPivot: "Y", style: "VICE NWH NAVY WHITE DC [ M450MBON ]"} 2. obj2 = { bookRetail: 14.99, hier ...

Issue with React component not receiving dataThe values are not being

Currently, I am a beginner in using React and as part of my training, I have embarked on a project to create a simple book ranking system. In this project, the user enters the title of the book they would like to vote for. If the input field is left empty, ...

Unable to reach the sub-component of the JSON object that was returned

For some reason, I can't seem to access a sub object of a returned $Resource object that fetched a group of JSON objects. It's baffling me. Resource > $resolved: true > $then: function (b, g) {var j=e(),h= > data: Object > 519bc5f6 ...

Double check for any identical items before proceeding to add them

Hey there! I need some help with pushing new items to an array without duplicating any elements. I've tried using this example, but it didn't work with our code. If anyone has a better solution or can spot where we're going wrong, please l ...

Breaking up React code within the React.createElement() function

I am encountering an issue with lazily loaded pages or components that need to be rendered after the main page loads. When using createElement(), I receive the following error: LazyExoticComponent | LazyExoticComponent is not assignable to parameter of ty ...

Error: The value of the expression has been altered after it was already checked. Initial value was 'undefined'. An exception has occurred

Although this question has been asked multiple times, I have read similar issues and still struggle to organize my code to resolve this particular exception. Within my component, there is a property that dynamically changes based on a condition: public e ...

Having trouble accessing parameter values in a React app using ES6 arrow functions

Hey there! I've been attempting to send values to an ES6 arrow function in my React application, but unfortunately, it's not working. Here's what I'm trying: var data = []; for (var i=1; i<=5; i++) { data.push(<li><a href ...

Using TypeScript to create a state object in Koa

I am currently utilizing Koa () as the framework for my backend, which consists of Node.js + TypeScript. Koa permits and recommends using the built-in `ctx.state` to store and pass data between different middleware functions. I have been adhering to this ...

Implementing AngularJS html5mode alongside nodeJS and Express

Currently, my AngularJS application is being served by a nodeJS server with Express. Everything runs smoothly when using the default angularJS routes (hashbangs); however, I am now attempting to enable html5 mode. To activate html5mode, I have implemented ...

A method for handling specific subsets of an enum in a secure and controlled manner

I have an enumerated type called Country and another type that represents a subset of European countries. I want to handle values within this subset differently from others. Currently, I am using an if statement with multiple conditions, but it could get u ...

Removing the previous value in React by shifting the cursor position - a step-by-step guide

I have successfully created a phone using React that saves the numbers in an input field whether you press the keys or use the keyboard. Although the phone is functioning well, I am facing an issue where pressing the delete button or backspace key always ...

Exploring ways to cycle through a select dropdown in React by utilizing properties sent from the Parent Component

I'm having trouble displaying the props from a parent component in a modal, specifically in a select dropdown. How can I make it so that the dropdown dynamically shows the values from the props instead of the hardcoded 'Agent' value? What am ...

Ways to generate an Angular 7 component

Seeking guidance on creating an angular 7 component. I have forked a jsFiddle at this link: https://jsfiddle.net/gauravshrestha/fdxsywLv/. The chart in the fiddle allows data points to be dragged up and down. My goal is to convert this into a component whe ...

How to retrieve the value from a JSON object when the key is unknown in JavaScript

Here is the JSON file I'm working with: { "status": 200, "msg": "OK", "result": { "files": { "count": 1, "pUnJbKzql0f2": { "name": "How ...

What is the best way to enhance a React Native component's properties with Flow?

I'm currently working with Flow version 0.54.1 in my React Native project, specifically using version 0.48.3. I have developed a component named PrimaryButton that acts as a wrapper for the native TouchableOpacity component. My goal is to define custo ...