Tips for including characteristics in an object while inheriting interfaces

In a nutshell, I have an issue where I have two interfaces: User and SpecialUser. The User interface has an 'attributes' object with certain properties, while the SpecialUser interface requires the 'attributes' object to include additional properties not found in User. The problem arises when the new attributes object overwrites the old one instead of merging them together. Although I could make it work by copying all properties from the parent interface and then adding the later ones, this solution is far from ideal.

export interface User{
  attributes: {
     full_name: string;
  }
}

export interface SpecialUser extends User {
  attributes: {
     occupation: string;
  }
}

My goal is for SpecialUser's 'attributes' to combine the fields from User's 'attributes' with its own new properties (such as full_name and occupation). Unfortunately, the current outcome is that it completely replaces the original attributes.

Answer №1

To implement a solution, one can consider utilizing an intersection type.

interface Person {
  details: {
    first_name: string;
  };
}

type SpecialPerson = {
  details: {
    occupation: string;
  };
} & Person;

const individual: SpecialPerson = {
  details: {
    occupation: "position",
    first_name: "John"
  }
};

TypeScript Playground

Answer №2

Encountered a similar issue, but opted to stick with interfaces rather than types. My solution is reminiscent of skovy's approach, with the only difference being the intersection moved into the interface:

interface Person {
  details: {
    name: string;
  };
}

interface SpecialPerson extends Person {
  details: {
    job: string;
  } & Person["details"];
};

const individual: SpecialPerson = {
  details: {
    job: "developer",
    name: "John Doe"
  }
};

TypeScript Playground

Answer №3

Do you think this solution would meet your requirements?

export interface Person {
  details: {
     first_name?: string;
     last_name?: string;
  }
}

Alternatively, if you need to extensively modify the details:

export interface Details {
    first_name: string;
}

export interface EnhancedDetails extends Details {
    //contains all original properties of details (e.g. first_name)
    last_name: string;
}

export interface Person {
    details: Details
}

export interface EnhancedPerson extends Person {
    details: EnhancedDetails //replaces original details
}

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

Exploring the implementation of TypeScript Generics in react-hook-form interfaces

This is the code I have: export interface PatientFormInputs { patientId: string; firstName: string; lastName: string; email: string; day: string; month: string; year: string; } In a React component: const { control, register, h ...

Rollup is encountering challenges with handling dependencies that are TypeScript files, resulting in an error being thrown: "Unexpected token."

Check out this GitHub repository for a sample project that showcases the issue. Here is the content of my package.json: { "name": "rollup-ts-deps", "version": "1.0.0", "description": "", ...

What is the process for including a unique attribute for child elements within a React component using TypeScript?

I have a component that creates a Table of Contents (TOC) and List for the child elements. These children can be any JSX.Element. Here is an example... <SectionScrollList> <View key="first"/> <View key="second"/> ...

Adding flair to a object's value in React JS

In my React JS file, I have a map function that I am using to populate a select dropdown with options. const options = response.map(k => ({ value: k.id, label: k.description ? `${k.name} - ${k.description}` : k.name, })); I ...

Errors encountered when using Input onChange with React and TypeScript: jsx no-lambda and no-bind issues

While creating a demonstration for a simple task, I encountered some challenges with the taskNameInput component. Despite my attempts, I kept encountering errors. How can I resolve these issues in React when using Typescript? You can refer to my GitHub re ...

Merging all Angular 2 project files into a single app.js document

I've scoured the depths of the internet for an answer to this burning question: How can I merge all my Angular 2 code, along with its dependencies, into a single file? Although this query has been posed countless times before, I bring a fresh perspect ...

Invalid Date - Issue with converting the string "MM/YYYY" to a Date format

When trying to convert a string to Date, I keep encountering an error message stating Invalid Date. The input will consist of a String with one of the following data formats: YYYY - year only MM/YYYY - month & year DD/MM/YYYY - full date While the ...

Tips on optimizing data processing for quicker display with ngFor

I am currently facing an issue with loading a JSON file containing 3500 data. The data appears very slowly on the view, causing the application to work sluggishly. Below is a snippet of the JSON: export class Service { private items = new Arr ...

In MUI React, the opacity of the placeholder is customizable and can be easily adjusted. This allows for the placeholder to be hidden

Currently, I am facing an issue with a filled variant TextField from Mui React. I have tried to modify it using theme components, but the placeholder text becomes hidden when the field is not focused. See here for Before Focus And here for On Focus I hav ...

Utilizing sourcemaps in ionic for seamless linking

I've encountered an issue with source maps or a similar feature. After inserting console.log(...) in my code, the message appears in the console but links to the compiled JavaScript file instead of the original TypeScript file. Have I overlooked som ...

Hearing from a variety of Observables within a Stream

I'm really struggling to grasp this concept. I have a container that is monitoring a dialog, which can emit various actions. Depending on the emitted action, I need to execute additional logic. I want to achieve this without using nested subscriptions ...

Leverage the power of React, Material-UI, and Typescript to inherit button props and incorporate a variety of unique

Looking to enhance the Material-UI button with additional variants like "square." How can I create a prop interface to merge/inherit props? Check out the following code snippet: import React from "react"; import { Button as MuiButton } from "@material-u ...

Definition of TypeScript type representing the value of a key within an object

As I delve into defining custom typings for a navigation library using TypeScript, one challenge that has me stumped is creating a navigate function. This function needs to take the Screen's name as the first argument and the Screen's properties ...

Utilizing Angular's global interceptor functionality can streamline the process

Having trouble making 2 interceptors (httpInterceptorProviders, jwtInterceptorProviders) work globally in my lazy modules. I have a CoreModule and X number of lazy-loaded modules. Interestingly, autogenerated code by the Swagger generator (HTTP services) g ...

Error encountered in Angular2: Attempted to access property 'compilerOptions' which is undefined

I encountered a TypeError: Unable to access the 'compilerOptions' property of undefined Below is the snippet of my compilerOptions code: { "compilerOptions": { "target": "ES5", "module": "commonjs", "emitDecoratorMetadata": tr ...

Angular 2 error: "unknown element" issue persists despite exhausting all attempted solutions

Here's a typical scenario where I attempt to incorporate a component from another module : External component : import { Component, ViewEncapsulation, ElementRef, ViewChild, Input, Output, EventEmitter } from '@angular/core'; declare ...

What is the best way to display three elements in a sequence while looping through a collection of elements in Angular 7?

When using Angular, I am trying to display a specific number of elements in a row from a list of items. I attempted to replicate the <tr> tags in my Angular code, but so far have been unsuccessful. Here is what I tried: <table class="table table ...

transferring attributes from a higher component to a lower one (modal)

https://i.sstatic.net/tSXb5.png https://i.sstatic.net/H4xmj.png I am relatively new to React and I want to share a detailed problem description: I have a Todo project that consists of multiple interfaces. The main interface displays all the lists, each ...

The View is not reflecting changes in the Variable

Is there a way to disable all the buttons when selectedplace is null in the Dialog, as it currently works when the Dialog first starts but remains activated all the time when the option is changed? I have attempted the following: Customized HTML: ...

A service worker of unknown origin is currently getting registered

Currently, I am using the service worker provided in create-react-app. After registering it in index.tsx with serviceWorker.register();, everything seems to be working fine. However, upon closer inspection in the dev tools' Application tab, I noticed ...