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

Guide on navigating an array of objects using the provided keys as a starting point in Javascript/Typescript

Assuming I have an array of objects structured like this: const events: Array<{year: number, month: number, date: number}> = [ {year: 2020, month: 10, date: 13}, {year: 2021: month: 3, date: 12}, {year: 2021: month: 9, date: 6}, {year: 2021: mont ...

What causes the variation in typing behavior between specifying props directly on a component versus nesting them inside another prop?

Understanding the next component might be a bit tricky, so let's delve into it (Check playground): type Props<T> = { initValue: T, process: (value: T) => T } export const Input = <T,>({ initValue, process, }: Props<T>): ...

Failure to nest interfaces in Angular when mapping JSON responses

After calling my ASP.NET Core Web API, the JSON response appears as: [ { "driver": { "firstName": "TEST", "lastName": "LAST", "assignedRoute": "O_ROUTE" } }, { "driver": { "firstName": "First", "lastName": " ...

Is there a way to use a single url in Angular for all routing purposes

My app's main page is accessed through this url: http://localhost:4200/ Every time the user clicks on a next button, a new screen is loaded with a different url pattern, examples of which are shown below: http://localhost:4200/screen/static/text/1/0 ...

Choose a specific location on a vehicle illustration within a pop-up window. The image should be partitioned into 6 separate sections

I have a project for my client where they need to choose a car and then indicate where the damage is located on an image, which is divided into 6 sections. I'm struggling to figure out how to achieve this. I initially thought z-index would work, but ...

Construct an outdated angular project from scratch

I'm facing an issue with an old Angular project that I'm trying to build. After pulling down the code, running npm install @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9f9095bccdd2cbd2c8">[email p ...

RxJs: Generating an observable based on changes in a field's value

Is there a way to generate an Observable using the variable this.pending as its source? I'm looking to create an Observable that will produce a new feed each time the value of this.pending changes. For example, if I update this.pending to be false i ...

The combination of UseState and useContext in React Typescript may lead to compatibility issues

I attempted to integrate the context API with the useState hook but encountered difficulties when using TypeScript. First, let's create App.tsx: const App = () => { const [exampleId, updateExampleId] = useState(0); return ( <div> ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Correctly inputting MongoDB-specific collection methods which are currently defaulting to "any"

I'm facing an issue with typing Mongo collection method responses in my app. Specifically, I am having trouble finding a way to type the response of the deleteMany method. The documented response should look like this: { "acknowledged" : true, "delete ...

Learn how to bring a component into another component within Angular

I have developed a component named CopySchedulefromSiteComponent and now I am looking to import it into another component called SiteScheduleComponent. However, I am unsure of the correct way to do this. The CopySchedulefromSiteComponent contains one fiel ...

"Upon submitting a form in React JS, the components will automatically trigger a

Within my application, there is a Mobx storage in conjunction with a modal window component. The form within the modal window allows me to collect all the properties and push them into an array named 'cart' within the storage as an object. Take a ...

Step-by-step guide on deploying your Nestjs API on Google App Engine

Encountering a hurdle while trying to deploy my nestjs api on Google App Engine has left me puzzled. Despite initializing my google cloud project with the google sdk, an error thwarted my progress. To tackle this challenge, I made key adjustments in my cod ...

Why am I unable to retrieve the property from the JSON file?

Below is the provided JSON data: data = { "company_name": "חברה לדוגמה", "audit_period_begin": "01/01/2021", "audit_period_end": "31/12/2021", "reports": [ ...

The ListItemButton's onclick event does not trigger on the initial click when utilizing a custom component as its children

I am having trouble comprehending why this onclick function is influenced by the children and how it operates <ListItemButton onClick={() => onClickResult(q)}> <Typography variant="body1">{highlighted}</Typography> ...

Retrieving the location.host parameter within NgModule

I am currently working on integrating Angular Adal for authenticating my application's admin interface with Azure AD. However, I have encountered a challenge with the redirectUri setting. My goal is to dynamically retrieve the current app's host ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

Implement a T3 App Redirect in a TRPC middleware for unsigned users

Is there a way to implement a server-side redirect if a user who is signed in has not finished filling out their profile page? const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCE ...

SonarQube flagging a suggestion to "eliminate this unnecessary assignment to a local variable"

Why am I encountering an error with SonarQube? How can I resolve it since the rule page does not offer a specific solution? The suggestion is to eliminate the unnecessary assignment to the local variable "validateAddressRequest". validateAddress() { ...