Inheritance of Type Member in TypeScript

My data structure looks like this:

export abstract class Person {
    ...
}

export class FPerson extends Person {
    a: A;
    b: B;
}

export class JPerson extends Person {
    c: C;
}

export class User {
    person: Person;
}

When dealing with the same structure written in Java on the server side, the User's person member can either be FPerson or JPerson. I need to cast it based on the person type. How can I achieve this in Typescript?

For example:

doSomething(u: User) {
    let fp: FPerson;
    let jp: JPerson;

    if (u.person.isFPerson()) {
       fp = <FPerson> u.person;
    } else {
       jp =  <FPerson> u.person;
    }
  ...
}

How do I create the isFPerson() method? And how can I ensure that TypeScript stores the additional fields from FPerson and JPerson into a Person variable?

Answer №1

Similar to the concept in Java:

performAction(user: User) {
    let femalePerson: Female;
    let malePerson: Male;

    if (user.person instanceof Female) {
       femalePerson = <Female> user.person;
    } else {
       malePerson = <Male> user.person;
    }
  ...
}

However, both Female and Male must inherit from Person, unlike the scenario presented in your question.

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 type '{ children: ReactNode; }' does not share any properties with the type 'IntrinsicAtrributes'

I have explored several discussions on the topic but none of them have provided a solution to my issue. My objective is to develop a reusable Typography component that resembles the following structure: import React from 'react' import type { Ty ...

Ensure that the array is completely populated before calling it in Angular

My code starts with an empty array and I need to call a service that works with the populated array. Two service calls are used to populate the array, both fetching elements from an API. The issue is ensuring the last service call waits for the array to be ...

The number type in Typescript is incompatible with the string type and cannot be assigned

Currently, I am deeply involved in developing a currency formatting directive for my Angular 4 application. In the parsing process, I am stripping out all characters except digits and decimal points to convert the input into a float number. However, I ne ...

Angular 7 running slowly when refreshing or changing routes

Operating System: Ubuntu 16.04 Node Version: v10.15.1 NPM Version: 6.4.1 I have recently developed a web application with two pages using less and HTML without any AJAX calls. Below is the content of my package.json file: { "name": "frontend", "vers ...

NestJS enforces HTTPS for Swagger redirects, whereas other endpoints are allowed to work on HTTP

I'm running into a strange problem with the Swagger interface on my NestJS server, which is hosted on a Windows Server environment and managed by PM2. While all other endpoints work fine over HTTP, the Swagger interface can only be accessed via HTTPS. ...

Issues with Angular 5 and Firebase integration

After updating my computer to High Sierra with a clean install, reinstalling the angular-cli, and cloning one of my previous projects that uses Firebase and angularfirebase2, I encountered an issue where any operation to get data from Firebase is not worki ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

Utilize Angular 4 to dynamically load templates within a single component

My task is to create a component with multiple HTML templates, each containing at least 20 controls. Depending on certain conditions, a specific template should be loaded. Note: I have opted for 3 different templates because the controls vary based on the ...

Utilizing Loops to Generate Unique CSS Designs on an HTML Page

View reference image ->Take a look at the reference image provided. ->In the image, a for loop is used to create box designs and displayed above. ->The goal is to change the background color and border color of all boxes using a single HTML cla ...

Tips on sending a list via @Input using Angular5

I was seeking guidance on how to pass a list through an input. In my parent component, I have the following: list: Hero[] = [{Id: 2, Name: "Sll"}, {Id: 3, Name: "Sldsadasd"}] and in the HTML: <app-add-hero list="{{list}}" hero={{hero}}></app-ad ...

What happens when arithmetic operators are applied to infinity values in JavaScript?

Why do Arithmetic Operators Behave Differently with Infinity in JavaScript? console.log(1.7976931348623157E+10308 + 1.7976931348623157E+10308)//Infinity console.log(1.7976931348623157E+10308 * 1.7976931348623157E+10308)//Infinity console.log(1.797693134 ...

Issue with handling http errors and navigating routes in Angular 2

Whenever I check a user's token authentication and encounter a 401 error, I aim to redirect them to the login page. The issue arises when attempting to navigate to the login page within the error catch block. constructor(private http: Http , private ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

Trouble arises when attempting to generate maps using leaflet.js with data sourced from a local directory

I've been working on an application that requires a map to function offline. I followed a tutorial, which you can find here: To create the necessary files, I generated an mbtiles file of my desired area at this link: The mbtiles file was saved as &a ...

Creating a map in Typescript initialized with a JSON object

In my Typescript class, there is a map that I'm trying to initialize: public map:Map<string,string>; constructor() { let jsonString = { "peureo" : "dsdlsdksd" }; this.map = jsonString; } The issue I'm encounte ...

issue encountered when implementing slick.js in angular 6

Trying to implement slick.js, a carousel framework, in an Angular project. Initially attempted 'npm install slick --save' and manually adding the downloaded files to scripts and styles JSON objects. When that failed, resorted to importing the C ...

Using Angular 6 and Reactive Forms can pose a challenge when attempting to programmatically set the select option while utilizing objects and the [selected

I'm really stuck on this issue. In my Angular project, I have two reactive forms that both contain a select control with options stored in class variables. One form uses basic option strings for employee choices like: ["Dan Smith", "Mark Johnson", e ...

Angular 5 does not recognize the function submitEl.triggerEventHandler, resulting in an error

Greetings! I am currently working on writing unit test cases in Angular5 Jasmine related to submitting a form. Below is the structure of my form: <form *ngIf="formResetToggle" class="form-horizontal" name="scopesEditorForm" #f="ngForm" novalidate (ngSu ...

Accessing Facebook in Ionic 2 Release Candidate 0

I'm interested in adding a Facebook login feature to my Ionic 2 app, but I'm unsure of how to proceed. Most tutorials I've come across demonstrate how to do this with Firebase database, while my project is already using MySql. Can someone gu ...

Accessing JSON data from a database using Angular

Wondering if there is a way to effectively access and manipulate JSON data stored in a database using Angular. While researching online, I keep coming across methods for reading JSON files from the Asset Folder, which does not align with what I need. What ...