What is the most efficient way to include a new subfield in a TypeScript interface child without duplicating existing

Imagine we have a base interface named Foo:

interface Foo {
  a: string;
  b: {
    c: string;
  }
}

Now, I wish to create a child interface called FooChild, which extends Foo by adding a new field d: string nested inside the existing b field.

interface FooChild extends Foo {
  a: string;
  b: {
    c: string;
    d: string;
  }
}

Is there any way to define FooChild more succinctly without explicitly mentioning the existing fields like a and c? For example:

interface FooChild extends Foo {
  // a: string; // this is fine
  b: {
    // c: string; // encountering an issue - Property c is missing...
    d: string;
  }
}

While omitting individual fields may work if you only have one field in b, it becomes cumbersome when dealing with a large number of fields. The repetitive nature of having to list all existing fields just to add a single new one can lead to code duplication.

Answer №1

My approach in solving this may differ slightly from what you were expecting. To begin, I defined the child interfaces as FooC and FooCD. Next, I created the parent interface (Fooo) with a generic type T, which will be one of the child interfaces. After that, I developed the child interfaces by extending the parent and specifying the generic type.

interface FooC {
  c: string
}

interface FooCD {
  c: string
  d: string
}

interface Fooo<T> {
  a: string
  b: T
}

interface FooWithC extends Fooo<FooC> {}
const c: FooWithC = {
  a: "a",
  b: {
    c: 'c'
  }
}
interface FooWithCD extends Fooo<FooCD> {}
const cd: FooWithCD = {
  a: "a",
  b: {
    c: 'c',
    d: 'd'
  }
}

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

Update an object by replacing its value with a new one, then add the updated object to an

I am attempting to clone and update an object in order to store it as a new instance in an array, but I am encountering some issues. Can anyone assist me in resolving this issue? Here is my code snippet: public getAppPropeties(locales):Observable<an ...

Dealing with Cross-Origin Resource Sharing problem in a React, TypeScript, Vite application with my .NET backend

I'm encountering a CORS issue when trying to make a Request using Fetch and Axios in my application hosted on the IIS Server. Here are my Server API settings: <httpProtocol> <customHeaders> <add name="Access-Control-Allow-O ...

What are the best practices for integrating PrimeVue with CustomElements?

Recently, I decided to incorporate PrimeVue and PrimeFlex into my Vue 3 custom Element. To achieve this, I created a Component using the .ce.vue extension for the sfc mode and utilized defineCustomElement along with customElements.define to compile it as a ...

Next.js does not recognize the _app file

After including the _app.tsx file in my project to enclose it within a next-auth SessionProvider, I noticed that my project is not recognizing the _app.tsx file. Even after adding a div with an orange background in the _app.tsx file, it does not reflect in ...

Pay attention to modifications in a property within an object in the React environment

Below is a React Context Provider containing a simple Counter class with methods stored in the context. import { createContext, useContext } from "react"; class Counter { public count: number = 0; getCount = () => { return this.count ...

The confusion arises from the ambiguity between the name of the module and the name of

In my current scenario, I am faced with the following issue : module SomeName { class SomeName { } var namespace = SomeName; } The problem is that when referencing SomeName, it is pointing to the class instead of the module. I have a requireme ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

Jasmine's await function often leads to variables remaining undefined

When testing a function, I encountered an issue where a variable is created and assigned a value, but the payload constant always remains undefined. campaigns-card.component.ts async ngOnInit() { const { uid } = await this.auth.currentUser const { ...

Display an image on an HTML page based on the TypeScript data in an Ionic Angular application

After retrieving user profile data from the database and storing it in an observable, I am able to access properties such as profileData.username, profileData.msgnumber, and more. When profileData.avatar returns the name of the avatar the user is using, I ...

Customizable JSX Attributes for Your TSX/JSX Application

Currently, I am in the process of converting my React project from JavaScript to TypeScript. One challenge I encountered is that TSX React assumes all properties defined in a functional component are mandatory props. // ComponentA.tsx class ComponentA ext ...

What might be the underlying reason for Chrome displaying a net::ERR_FAILED error when attempting to make a request from a Vue frontend to a C# API using Axios?

I have a C# Backend+API that I interact with from my Vue Application using axios to make requests. In the C# code, there is an endpoint that looks like this: // GET: api/Timezone public HttpResponseMessage GetTimezoneData() { ...

What is the safest method to convert a nested data structure into an immutable one while ensuring type safety when utilizing Immutable library?

When it comes to dealing with immutable data structures, Immutable provides the handy fromJs function. However, I've been facing issues trying to integrate it smoothly with Typescript. Here's what I've got: type SubData = { field1: strin ...

When intercepted, the HttpRequest is being canceled

Solution Needed for Request Cancellation Issue Encountering a problem with the usage of HttpInterceptor to include the Authorize header in all HTTP requests sent to AWS API Gateway. The issue arises as all these requests are getting cancelled when interce ...

Utilizing TypeScript to access global variables and external libraries

Currently, I am in the process of converting traditional JavaScript files into TypeScript for use in client-side deployments within SharePoint. Within SharePoint, there are global variables and libraries that we rely on without needing to explicitly load t ...

Determine whether a nullable string property contains a specific string using indexOf or includes may result in an expression error

I am facing a challenge where I need to assign a value conditionally to a const. The task involves checking if a nullable string property in an object contains another nullable string property. Depending on the result of this check, I will then assign the ...

Encountering a type-safety problem while attempting to add data to a table with Drizzle

My database schema is structured like so: export const Organization = pgTable( "Organization", { id: text("id").primaryKey().notNull(), name: text("name").notNull(), createdAt: timestamp("c ...

Is it necessary to compile the ngfactory files during Angular 2 AOT compilation?

I've noticed an interesting behavior when compiling my Angular 2 application with `ngc`. During the first run, it generates the `.ngfactory.ts` files for each component but only compiles the TypeScript to JavaScript for other files. This results in no ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

Steps for linking Apollo client to Apollo server

I'm currently working through the Apollo tutorial located at https://www.apollographql.com/docs/tutorial/client/. My server is successfully running on localhost:4000, while my client is running on localhost:3000. Even though the client compiled withou ...

Troubleshooting Angular 14 Custom Form Control Display Issue

I'm facing an issue while attempting to develop a custom form control in Angular 14. Despite no errors showing up in the console, my custom control is not rendering as expected. When inspecting the Elements tab in the console, I can see the parent com ...