Using TypeScript to deserialize various types from a shared object

I am currently dealing with a JSON array containing serialized objects, each of which has a type field. My challenge lies in deserializing them properly due to TypeScript not cooperating as expected:

Check out the TypeScript playground for reference.

type serializedA = { type: 'A', aProp: string };
class A {
    public type = 'A';
    constructor(data: serializedA) {}
}

type serializedB = { type: 'B', bProp: string };
class B {
    public type = 'B'
    constructor(data: serializedB) {}
}

const classMap = { A, B };

function deserialize(serializedObject: serializedA | serializedB) {
    const Klass = classMap[serializedObject.type];
    new Klass(serializedObject);
}

The problem arises from the last line where TypeScript is unable to determine whether Klass and serializedObject are now both instances of A or B. I'm struggling to find a way to clarify this to TypeScript.

Answer №1

Looking for top-notch decoding libraries suitable for production use? Check out these recommendations:

We have been heavily relying on io-ts in our projects. For more information, you can find it here

Answer №2

interface SerializedData {
    type: string;
    prop: string;
}

class CustomClass {
    public type: string;
    constructor(data: SerializedData) {}
}

const classDictionary = { A: CustomClass, B: CustomClass };

function deserializeObject(serializedObj: SerializedData) {
    let Klass = classDictionary[serializedObj.type];
    return new Klass(serializedObj);
}

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 application's functionality is interrupted when router.navigate() is called within the .subscribe method

I am having an issue with user navigation on my application. After successfully signing in, users get redirected to the home page (/), but they are unable to navigate by clicking any links on that page. Upon further investigation, I discovered that moving ...

Angular example of Typeahead feature is sending a blank parameter to the backend server

I am currently trying to implement a similar functionality to the example provided at this link in my Angular frontend application. The goal is to send a GET request to my backend with the search parameter obtained from an input field. However, even thoug ...

What is causing the failure of the state to be inherited by the child component in this scenario (TypeScript/React/SPFX)?

For this scenario, I have a Parent class component called Dibf and a Child class component named Header. While I can successfully pass props from the Parent to the child, I am encountering difficulties when trying to pass state down by implementing the fo ...

Can you explain the purpose and functionality of the following code in Typescript: `export type Replace<T, R> = Omit<T, keyof R> & R;`

Despite my efforts, I am still struggling to grasp the concept of the Replace type. I have thoroughly reviewed the typescript documentation and gained some insight into what is happening in that line, but it remains elusive to me. ...

The IDE is able to detect interface extensions in d.ts files, but TypeScript is not recognizing them

When developing in ES6 style module inclusion within WebStorm, I encountered an issue with my Express app and a custom d.ts file. The d.ts file contains middleware that alters objects, and the structure looks like this: declare module Express { export ...

Create a new instance of the parent class in TypeScript to achieve class inheritance

Looking for a solution to extending a base class Collection in JavaScript/TypeScript to handle domain-specific use cases by implementing a "destructing" method like filter that returns a new instance with filtered elements. In PHP, you can achieve this usi ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

Google Maps on Angular fails to load

I'm currently working on integrating AGM into my Ionic 2 project. app.module.ts ... import { AgmCoreModule } from '@agm/core'; import { DirectionsMapDirective } from '../components/directions-map'; @NgModule({ declarations: [ ...

Error messages encountered following the latest update to the subsequent project

Recently, I upgraded a Next project from version 12 to 14, and now I'm encountering numerous import errors when attempting to run the project locally. There are too many errors to list completely, but here are a few examples: Import trace for requeste ...

What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections). When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs. But ...

Is it possible to specify broad keys of a defined object in TypeScript using TypeScript's typing system?

const obj: {[key: string]: string} = {foo: 'x', bar: 'y'}; type ObjType = keyof typeof obj; Is there a way to restrict ObjType to only accept values "foo" or "bar" without changing the type of obj? ...

"Error: Unfinished string literal encountered" occurring in a TypeScript app.component.ts file in NativeScript

I've been trying to learn NativeScript through a tutorial, but I keep encountering errors. Here is an excerpt from my app.component.ts file: import { Component } from '@angular/core'; @Component ({ selector: 'my-app', temp ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Is there a workaround for utilizing a custom hook within the useEffect function?

I have a custom hook named Api that handles fetching data from my API and managing auth tokens. In my Main app, there are various ways the state variable "postId" can be updated. Whenever it changes, I want the Api to fetch new content for that specific p ...

In Angular 6, triggering a reset on a reactive form will activate all necessary validators

As a beginner in angular 6, I am currently facing an issue with resetting a form after submitting data. Although everything seems to be functioning properly, when I reset the form after successfully submitting data to the database, it triggers all the req ...

Tips for streamlining a conditional statement with three parameters

Looking to streamline this function with binary inputs: export const handleStepCompletion = (userSave: number, concur: number, signature: number) => { if (userSave === 0 && concur === 0 && signature === 0) { return {complet ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

New Entry failing to appear in table after new record is inserted in CRUD Angular application

Working with Angular 13, I developed a basic CRUD application for managing employee data. Upon submitting new information, the createEmployee() service is executed and the data is displayed in the console. However, sometimes the newly created entry does no ...

Tips and tricks for sending data to an angular material 2 dialog

I am utilizing the dialog box feature of Angular Material2. My goal is to send data to the component that opens within the dialog. This is how I trigger the dialog box when a button is clicked: let dialogRef = this.dialog.open(DialogComponent, { ...

What is the best way to perform a deep copy in Angular 4 without relying on JQuery functions?

Within my application, I am working with an array of heroes which are displayed in a list using *ngFor. When a user clicks on a hero in the list, the hero is copied to a new variable and that variable is then bound to an input field using two-way binding. ...