Serializing a mixed-type array

I have an array in TypeScript that looks like this:

const baseElements: IBaseElement[]

An IBaseElement contains some information:

export interface IBaseElement{
a: number;
b: string;
}

There are two classes that implement the IBaseElement interface:

export class A implements IBaseElement{
}

export class B implements IBaseElement{
}

The classes A and B are stored in the baseElements array (baseElements.push(A)....)

While using instanceof, I can determine if the element is of type A or B. However, when the data is serialized to JSON and saved in a database, my concern arises.

My question is, will I be able to distinguish between the two types when retrieving the data from the database?

If there are any areas where my question lacks clarity, please inform me. Thank you in advance.

Answer №1

When the need arises to create two new classes, it signals a divergence in the JSON schema from the original interface.

This implies that when fetching JSON data from your database, you will have to explicitly convert it. For instance, if you are working with Angular + RxJS, your code should end up looking like this:

return http.get(this.url)
           .map(response => response.json().data as A)

as illustrated in the angular tutorial

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

The class function in the exported typescript logs that "this" is not defined

I am currently facing an issue with my TypeScript class where I am setting class values in a constructor and referencing them using "this" in a class method. While the .ts file compiles without any warnings, when I import the compiled .js file into another ...

Link that updates periodically linked to an image

My goal is to have a URL change on a timer that is linked to an image. For example, after 10 seconds, I want the URL attached to the image to change without changing the actual image itself. I've been trying to figure out how to modify this code, but ...

"Converting a regular JavaScript array into a JSON object: A step-by-step

I have an array that currently looks like this: ['service1', 'service2', 'service3'] and I want to convert it into something like: [ {'id':'1', 'serviceName':'service1'}, {'id& ...

Place the `service` parameter into the `run` function

What are some examples of when to utilize the angular.run method? I have a service that is resource-intensive and takes a significant amount of time to initialize before it can be used in conjunction with my view. angular.module('myApp').service ...

Loop through the coefficients of a polynomial created from a string using JavaScript

Summary: Seeking a method to generate a polynomial from specified coordinates, enabling coefficient iteration and optional point evaluation I am currently developing a basic JavaScript/TypeScript algorithm for KZG commitments, which involves multiplying c ...

Is there a way to set up an HTTP service in Orbeon by utilizing HTTP parameters and extracting data from a JSON response?

Currently, I am exploring the potential of Orbeon for creating forms within my application. This particular application makes use of HTTP web services by passing and receiving JSON data through HTTP parameters. I would like to know how I can set up Orbeon ...

Is it possible to update a Rails element using an AJAX request?

I've delved into a plethora of information regarding Rails, AJAX, and 5.1 Unobtrusive Javascript. It provides insight on how to handle AJAX calls in Rails with a .js file, for example. However, my goal isn't to serve up an entire .js file; rathe ...

Ways to complete a progress bar up to 100% based on the user's specified time

I'm currently developing a progress bar for a pomodoro timer. The concept is for this bar to reach 100% completion based on the specified time of the pomodoro session. For instance, if the session is set for 30 minutes, the progress bar should be full ...

The sessionToken is invalidated upon the user updating their password

My mobile hybrid app is connected to an expressJS server that acts as the backend for proxying requests to parse.com through the REST API. Additionally, I have implemented user authentication using express with a Single Sign-On (SSO) provider. Although I f ...

Activating the Submission of a File in a JQuery Form Plugin

Currently, I am using the JQuery Form Plugin to facilitate file uploads on my website. Instead of using a standard submit button, I would prefer to have a div element trigger the submission process. Here is the code I have attempted: $(document).on(&apo ...

Sending Disabled Form Field Input Value in Angular 2 POST Request

I'm working on a form with an email field that I want to populate using interpolation. However, I also want to prevent users from changing the email address once it's displayed. To achieve this, I tried adding the disabled attribute to the input ...

What is the best way to sort a union based on the existence or non-existence of a specific

My API response comes in the form of a IResponse, which can have different variations based on a URL search parameter. Here is how I plan to utilize it: const data1 = await request<E<"aaa">>('/api/data/1?type=aaa'); const d ...

Laravel implementation of Bootstrap Datepicker

Incorporating Laravel bootstrap and a date picker, I have encountered an issue where the todayHighlight feature is not functioning correctly. Additionally, the container aspect is also not working as intended. <link rel="stylesheet" href="https://sta ...

Objects hidden in the darkness, utilizing the traditional MeshPhongMaterial

Currently struggling with my shadows issue. Here is a snapshot of the problem I am encountering: https://i.sstatic.net/odnuE.png https://i.sstatic.net/RZitM.png The presence of those lines puzzles me, as the scene should be evenly illuminated! The shado ...

How can you access the index of an object in Vue.js when one of its properties has been modified

Here's the Vue component code I'm working with: data: function () { return { products: [ { product_id: '', price: ''}, { product_id: '', price: ''}, ], ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

Converting an array of objects to an array of JSON objects in TypeScript

My dilemma lies in the data I have uploaded under the _attachments variable: https://i.sstatic.net/jnFNH.png My aim is to format this data for insertion in the following structure: "_attachments": [ { "container": "string", "fileName": "string" ...

Issue with DTO and a custom decorator in NestJS

I am currently facing an issue with using a DTO alongside a custom decorator within a NestJS controller for body validation. I am sending a request using multipart/form data, which requires me to parse the data from a string to JSON. However, when attempti ...

Sending data using JSON and HTTP POST method via URL

Is it possible for my servlet to receive 4 parameters through HTTP POST by using a URL? An illustration of the URL: http:///servlet The data that will be delivered will be in text form utilizing the JSON format. JSONObject myStr = new JSONObject(); I a ...

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...