Converting a TypeScript class to a plain JavaScript object using class-transformer

I have a few instances of TypeScript classes in my Angular app that I need to save to Firebase. However, Firebase does not support custom classes, so I stumbled upon this library: https://github.com/typestack/class-transformer which seems to be a good fit for my needs.

Now, I am working on creating my object and trying to convert it.

Here is an example of my object:

export class Trip {
  id: string;
  owner: string;
  name: string;
  @Type(() => Date)
  startDate: Date;
  @Type(() => Date)
  endDate: Date | undefined;
  coverImageUrl: string;

  @Type(() => Itinerary)
  itinerary: Itinerary;

  constructor() {
    this.itinerary = new Itinerary();
  }
}

//other class definitions...

I am currently creating a "trip" instance and attempting to convert it:

const trip = new Trip();
trip.owner= firebase.auth().currentUser.uid;
trip.name= action.name;
trip.startDate = action.startDate,
trip.endDate = action.endDate;
console.log(trip);
const converted = classToPlain(trip)

However, when I try to convert it, I encounter the following error:

ERROR TypeError: Cannot read the property 'constructor' of undefined
    // stack trace continues...

The object I just created: https://i.sstatic.net/GG3FC.png

I suspect that either my object is in an incorrect state or there is something poorly defined, but I'm having trouble pinpointing the issue.

Answer №1

The issue originates from the definition of Itinerary, particularly in the line of code this.steps = Step[0];. This sets the variable to undefined, which was most likely not intentional. The class-transformer library is capable of handling the property steps as an empty array, an array of steps, or even if it does not exist initially. However, it crashes when the value is specifically set to undefined.

export class Itinerary {
  @Type(() => ItineraryStats)
  stats: ItineraryStats;
  @Type(() => Step, {
    discriminator: {
      property: '__type',
      subTypes: [
        { value: ActivityStep, name: 'ActivityStep' },
        { value: NightStep, name: 'NightStep' },
        { value: PointOfInterest, name: 'PointOfInterest' },
        { value: TravelStep, name: 'TravelStep' },
      ],
    },
  })
  steps: Step[];

  constructor() {
    // Step[0] causes the crash, because its undefined, either dont set it or 
    // set it to this.steps = []
    this.steps = Step[0]; 
    this.stats = new ItineraryStats();
  }
}

Further details: As discriminators are used on the property steps, the corresponding logic activated and compared the constructors specified under subTypes with the constructor of the current value to determine the correct subtype name:

    if (this.transformationType === TransformationType.CLASS_TO_PLAIN) {
      subValue[targetType.options.discriminator.property] = targetType.options.discriminator.subTypes.find(
        subType => subType.value === subValue.constructor
      ).name;
    }

link to github

Step[0] being undefined eventually caused the line subValue.constructor to crash.

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

Unable to decrease the width of a div element in Vuetify and Nuxt

As I work on creating a dynamic form with fields that need to occupy only 50% of the size of a regular field, I encounter different components based on data provided by Vuex. The use of v-for in Vue.js helps me loop through form objects and render the app ...

Go back to the top by clicking on the image

Can you help me with a quick query? Is it feasible to automatically scroll back to the top after clicking on an image that serves as a reference to jQuery content? For instance, if I select an image in the "Portfolio" section of , I would like to be tak ...

Getting a file object with v-file-input in Nuxt.js

For my Nuxt.Js apps, I utilized Vuetify.js as the UI framework. In order to obtain the file object when uploading files, I incorporated the v-file-input component from Vuetify.js and wrote the following code snippet: <template> <div> ...

The inputs for Node express middleware are unclear and lack definition

I am currently exploring Node.js as a potential replacement for my existing DOT NET API. I have created middleware to enforce basic non-role authorization in my application, but I am encountering compilation problems with the function inputs. Compilation ...

conceal specific language options within the dropdown selection box

In my user interface, I have implemented a drop-down menu that allows users to select their preferred language. I want the selected language option to disappear from the drop-down menu once chosen. Here is the HTML code snippet: <li> < ...

I need to figure out a way to validate form data dynamically as the number of fields constantly changes. My form data is being sent via Ajax

Click validation is desired. It is requested that before transmitting data, the validate function should be executed. If there is an empty field, a message should be displayed and the data should not be sent to the PHP file. In case there are no empty fi ...

Issue with Ajax post redirection back to original page

I'm facing an issue with my ajax call where I send multiple checkbox values to a php file for processing and updating the database. The post request and database updates are successful, but the page doesn't return to the calling php file automati ...

The Date Picker pops up automatically upon opening the page but this feature is only available on IE10

There seems to be an issue with the date picker opening automatically on IE10, while it works fine in Firefox where it only appears when you click on the associated text box. Does anyone have insight into why this might be happening specifically in IE10? ...

Is there a way to access the sqlite3 database file in electron during production?

Currently, I have an electron application that I developed using the create-electron-app package. Inside the public folder of my Electron app, both the main process file and the sqlite3 database are located. During development, I can access the database ...

Javascript encountered an error upon attempting to return from the main function

I have a function that calls the database to perform an action: function callQuery(query) { db.query(query, (err, res) => { if (err) { // Error connecting to DB console.log(err.stack) } else { // Return the results ret ...

Utilizing long polling technique with jQuery/AJAX on the server end

Currently, I am facing an issue with long polling on a single page that contains multiple pages. The problem arises when a new request is made while a previous request is still processing. Even though I attempt to abort the previous request, it completes b ...

What is the best way to simulate a CSS import for a jest/enzyme test?

I am facing an issue with mocking an imported CSS file in my jest/enzyme test: Header.test.js import React from 'react' import { shallow } from 'enzyme' import { Header } from './Header' jest.mock('semantic-ui-css/sema ...

Accessing the current state outside of a component using React Context

As I delve into creating a React application, I find myself in uncharted territory with hooks and the new context API. Typically, I rely on Redux for my projects, but this time I wanted to explore the context API and hooks. However, I'm encountering s ...

Maximizing the efficiency of React.js: Strategies to avoid unnecessary renders when adding a new form field on a webpage

Currently, I have a form that consists of conditionally rendered fields. These components are built using MUI components, react-hook-form, and yup for validation. In addition, within the AutocompleteCoffee, RadioBtnGroup, and TxtField components, I have i ...

What is the best way to prevent the body from scrolling when scrolling on a fixed div without making the body's scroll bar disappear?

Is there a way to prevent the body from scrolling while I scroll on a fixed div? I attempted using overflow:hidden for the body, which stops scrolling but causes the page to shake when the scroll bar disappears. Is there a solution that allows me to keep ...

Accessing the URL causes malfunctioning of the dynamic routing in Angular 2

I am currently working on implementing dynamic routing functionality in my Angular application. So far, I have successfully achieved the following functionalities: Addition of routing to an existing angular component based on user input Removal of routin ...

Create an unordered Vue component object

In the data retrieved from the backend, there is an object containing various properties, one of which is the 'average' value. This object is ordered based on that value and when accessed through Postman, it appears as follows: ranking: ...

The issue at hand involves Javascript, Ajax, latte, and Presenter where there seems to be a restriction on using GET requests for a file located

I have a query. I’ve been given the task of adding a new function to our web application. It was built on PHP by someone else, so it's proving quite challenging for me to debug as I am not familiar with this technology. I’m attempting to incorpor ...

Using jQuery to iterate over a multi-dimensional array and showing the child elements for each parent array

I am facing an issue with a multidimensional array that contains objects and other arrays. While it is simple to loop through the parent array and display its contents in HTML, I encounter a problem when there are multiple layers of arrays nested within ea ...

What could be causing NPM to generate an HTTP Error 400 when trying to publish a package?

My current goal is to release an NPM package named 2680. At the moment, there is no existing package, user, or organization with this specific name. Upon inspection of my package.json, it appears that everything else is in order. Here are all the relevant ...