Customize optional nested properties inherited from interfaces

The interface I'm working with is structured as follows:

export interface InterfaceA {
    propA?: any;
}

export interface MyBaseInterface extends InterfaceA {
    propA?: {
        nestedPropA?: {
            nestedNestedPropA: string;
            nestedNestedPropB: string;
        };
    };
};

My goal is to extend MyBaseInterface while inheriting all its properties and adding additional ones. The desired outcome should look like this:

export interface MyNewInterface {
    propA?: {
        nestedPropA?: {
            nestedNestedPropA: string;
            nestedNestedPropB: string;
            nestedNestedPropC: string;
        };
    };
};

I attempted a few approaches based on this reference question. For example:

export interface MyNewInterface extends MyBaseInterface {
    propA?: MyBaseInterface['propA'] & {
        nestedPropA?: MyBaseInterface['propA']['nestedPropA'] & {
            nestedNestedPropC: string;
        };
    };
};

However, I encountered an issue where "MyBaseInterface does not have nestedPropA" error occurred due to it being optional. Making the props mandatory would not allow for overriding them. Using extends Required<> would enforce implementing unwanted properties.

If anyone can provide guidance or assistance, it would be greatly appreciated. Thank you.

Answer №1

It appears that you have reached the limits of interface inheritance in a natural way. As far as I know, Lookup types cannot handle this optional constraint, and Conditional types cannot be used for interfaces.

Type aliases provide much more flexibility when it comes to defining types and composing optional properties:

type A = {
  // your base properties
};

type B = A & {
  propA?: {
    nestedPropA?: {
      nestedNestedPropA: string;
      nestedNestedPropB: string;
    };
  };
}

type C = B & {
  propA?: {
    nestedPropA?: {
      nestedNestedPropC: string;
    };
  };
}

Please note that you cannot define propA?: any; in A, as the type of propA would become widened to any when creating intersection types, resulting in loss of strong typing. This can be demonstrated by:

type T1 = any
type T2 = string
type T3 = T1 & T2 // type T3 = any ; any wins

Here is a TS Playground link to the above example.

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

Is there a way to increase the level of detail in the error trace provided by tsc? This error trace is

While attempting to compile a React project using the default tsconfig.json provided by create-react-app, I encountered a baffling error that has me stumped. $ tsc error TS2488: Type 'never' must have a '[Symbol.iterator]()' method that ...

Create a dynamic styled component with tags based on props

Looking to craft a dynamic tag using styled components, where the tag is passed in via props. Here's an example of the code: import * as React from 'react'; import styled from 'styled-components'; type ContainerProps = { chi ...

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Populate Dialog Form with Parent Data in React using Typescript

Incorporating Reactjs and Typescript, I am facing an issue with a parent component that retrieves data from an API and then uses it to trigger the opening of a Material-UI Dialog containing an editable form. The problem lies in prepopulating the dialog wit ...

Is the 'el' property used in Vue along with TypeScript when working with vue-property-decorator/vue-class-component?

Keep this question short and sweet. How would you rewrite the code snippet below using TypeScript, Vue, and vue-property-decorator? @Component({ el: '#app', data() { return { message: 'Hello Vue!' } } }) export defa ...

Service layer constants unique to the implementation

My ASP.Net Web Forms project serves as a user interface for a CRM web service, among other things. In my project, I have an interface called IMembershipService, with various methods for purchasing subscriptions to a service. The concrete implementation of ...

Creating folders and writing data to text files in Angular 4/5 with TypeScript: A tutorial

Is it feasible to create a folder, text file, and write data into that file in Angular5 using Typescript for the purpose of logging errors? Your expertise on this matter would be greatly appreciated. Thank you in advance! ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

Deduce the argument type of a class from the super call

I'm currently working on a project utilizing the discord.js library. Within this project, there is an interface called ClientEvents which contains different event argument tuple types: interface ClientEvents { ready: []; warn: [reason: string] m ...

How to change a specific value in an array of objects using React

Within my array, I have objects containing the fields id and title const cols = [ { id: 0, title: "TODO" }, { id: 1, title: "InProgress" }, { id: 2, title: "Testing" }, { ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

Does the Fragment Developer Guide Have Inconsistencies?

The official Fragment guide's Design Philosophy section emphasizes designing each fragment as a modular and reusable activity component. By defining layouts, behaviors, and lifecycle callbacks within each fragment, you can easily include one fragment ...

The link function fails to execute

I have created a custom Directive. The issue I am facing is that the html template is not being rendered. Upon debugging, I noticed that the link function is never called because the instance function is also never called. To troubleshoot, I added "debu ...

Creating dynamic elements with Nativescript-Vue

Is there a way for me to dynamically generate new elements such as buttons, labels, or textfields within a layout? Here is the code snippet I currently have: <AbsoluteLayout ref="abs"> <Label :text="L('UserClockIn.info.5')" top="10 ...

Using Systemjs with Angular 2 results in 50 server calls for loading resources

While following the Angular2 quickstart tutorial on Angular.io, I noticed that it was making 50 separate requests, which left me wondering why. https://i.sstatic.net/bqMk8.png Is there a way to consolidate all these requests into one? My goal is to have ...

Each professional has their own unique workdays and hours, which are easily managed with the angular schedule feature

My schedule is quite dynamic, with professionals attending on different days for varying periods of time. Each professional has a different start and end time on their designated day. To see an example of this setup, you can visit the following link: Sche ...

Troubles encountered with ionic's usage of [innerHTML] within <ion-list>

Encountering an issue while using ionic 3 and angular 2 with styling a large HTML string using [innerHTML]. Strangely, the string gets cut off at the end of the screen instead of wrapping to the next line when placed within an ion-list tag. Any insights on ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

There was a problem rendering the error view configuration callback for the RCTModalHostView component - it must be a function, but it was received as 'undefined'

Working on a mobile application in React Native, specifically using Expo SDK version ~51.0.18 for development. The project involves utilizing the Expo router to manage all routing within the app. Now, I'm looking to implement a new SDK called Lean t ...