What are the steps to implementing interface polymorphism in Typescript?

This is my interface hierarchy:

interface parent {
    common: string;
}

interface child1 extends parent {
    prop1: string;
}

interface child2 extends parent {
    prop2: string;
}

My goal now is to create an interface with a property that is of type parent, meaning it can be either child1 or child2.

My attempt was:

interface SomeObject {
    member: parent;
}

let a: SomeObject = {
    member: {
        common: "a",
        prop1: "b"
    }
}

However, the compiler points out that prop1 is not a member of parent.

What is the correct approach to achieve this?

Answer №1

A common method for handling this situation is by utilizing a generic type:

interface base {
    shared: string;
}

interface sub1 extends base {
    property1: string;
}

interface sub2 extends base {
    property2: string;
}

interface CustomObject<T extends base> {
    data: T;
}

let obj: CustomObject<sub1> = {
    data: {
        shared: "x",
        property1: "y"
    }
}

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

Angular Material Datepicker: Changing the input field format when the field value is updated

Currently, I am utilizing a mat-date-rang-input component from Angular Material. To customize the date format to dd/MM/yyyy, I made adjustments within Angular Material which is functioning correctly. <mat-form-field ngClass="filters_dateInterval&qu ...

Refreshing HTTP request in Angular

I am currently working with Angular 5 and have encountered the following issue: Within my route, I have a parameter called year. The component related to this route is supposed to display data based on the year parameter, which is fetched from a service. ...

Stylish elements within a higher-order component in a React application

Encountering two problems when using styled components within a higher order component wrapper in react. The component is being rendered without the specified background color. Encountering TypeScript errors with the ComponentWithAddedColors. Unable to id ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Unable to determine the size of the array being passed as a parameter in the function

When passing an array as a parameter to a function, I aim to retrieve its length. Within my code, I am working with an array of objects. groupList:group[]=[]; Within the selectItem function, I invoke the testExistinginArray function. selectItem (event) ...

Performing a conditional query on a Many-to-Many relationship in TypeORM

Operating under a many-to-many relationship between Category and Product entities In need of filtering products based on category ID Attempted to implement the following code after referring to some examples, but encountered difficulties in making it fun ...

Convert all existing objects to strings

I have a type that consists of properties with different data types type ExampleType = { one: string two: boolean three: 'A' | 'Union' } Is there an easier way to define the same type but with all properties as strings? type Exam ...

Adding an additional element to an object - crossroads of combining types versus sequential examination

Here's a query for you: AppendToObject. When I first tackled this question, my initial instinct was to utilize type intersection like so: type AppendToObject<T, U extends PropertyKey, V> = T & {[P in U]: V} Unfortunately, this solution did ...

Selecting a radio button by clicking on its corresponding label within an Angular Material dialog

I recently implemented a custom rating bar in Angular, which worked perfectly fine in a basic component. However, when I tried to move it to a MatDialog component, I encountered some issues. In the initial setup, my input was set to display: none so that t ...

Adjust the height of a div vertically in Angular 2+

Recently, I started using angular2 and I've been attempting to create a vertically resizable div without success. I have experimented with a directive for this purpose. Below is the code for my directive: import { Directive, HostListener, ElementRef ...

Check out the uploaded file preview on React Native Expo!

I'm attempting to display a preview of the file uploaded by the user, which could be in pdf, img, or doc format. I tried a method that previews the file using a specific URL, but what I really want is for it to only show the preview of the uploaded fi ...

Having trouble with importing rxjs operators

After updating the imports for rxjs operators in my project to follow the new recommended syntax, I encountered an issue with the "do" operator. While switchMap and debounceTime were updated successfully like this: import { switchMap, debounceTime } ...

Is it feasible to verify the accuracy of the return type of a generic function in Typescript?

Is there a way to validate the result of JSON.parse for different possible types? In the APIs I'm working on, various Json fields from the database need to have specific structures. I want to check if a certain JsonValue returned from the database is ...

Retrieve the values of private variables within a defined function

While experimenting with typescript, I have encountered an issue that I can't seem to resolve. My project involves using Angular, so I will present my problem within that context. Here is a snippet of my code: class PersonCtrl{ private $scope: I ...

Transmitting form data inputted by the user to a modal that resides in the same component, all without the need for child or parent components or

In need of a solution where users can input answers to questions and have all the entered data displayed in a popup alongside the respective question. If a user chooses not to answer a question, I do not want that question or any related information to be ...

The error message "Property 'showUserDropdown' is not found on type '{}'.ts" indicates that the specified property is not present in the defined

While creating a basic Vue component, I encountered an error in the IDE regarding the {{ showUserDropdown }} with the message: Property 'showUserDropdown' does not exist on type '{}'.ts Despite adding it to data, <template> &l ...

Ensure the object is not null with this Object type guard

Is there a way to create a type guard for an object directly in TypeScript? I've written a function to check any input: export function isObject(input: any) :input is Record<string,any> { return (input !== null) && (typeof input == ...

Refreshing Angular2 View After Form Submission

Currently, I am in the process of developing a basic CRUD application with Angular2. The application comprises of a table that displays existing records and a form for adding new records. I am seeking guidance on how to update the table to show the new rec ...

There are several InputBase elements nested within a FormControl

There seems to be an issue: Material-UI: It appears that there are multiple InputBase components within a FormControl, which is not supported. This could potentially lead to infinite rendering loops. Please only use one InputBase component. I understand ...

"Enable email delivery in the background on a mobile app without relying on a server

I am currently in the process of developing a mobile app using Ionic. One feature I would like to incorporate is sending an email notification to admins whenever a post is reported within the app. However, I am facing challenges with implementing this succ ...