Using Typescript to create an interface that extends another interface and includes nested properties

Here is an example of an interface I am working with:

export interface Module {
  name: string;
  data: any;
  structure: {
    icon: string;
    label: string;
    ...
  }
}

I am looking to extend this interface by adding new properties to the 'structure' without repeating myself. Should I create a new interface for 'structure', extend it and then create a new Module with the updated 'structure' interface? Or is there another syntax that can achieve this in a more efficient way?

My ideal solution would be something like:

export interface DataModule extends Module {
  structure: {
    visible: boolean;
  }
}

export interface UrlModule extends Module {
  structure: {
    url: string;
  }
}

Thank you!

Answer №1

In the base interface, interfaces cannot add to the types of members directly. Instead, you can utilize an intersection type:

export interface Module {
    name: string;
    data: any;
    structure: {
        icon: string;
        label: string;
    }
}

export type DataModule = Module & {
    structure: {
        visible: boolean;
    }
}

export type UrlModule = Module & {
    structure: {
        url: string;
    }
}

let urlModule: UrlModule = {
    name: "",
    data: {},
    structure: {
        icon: '',
        label: '',
        url: ''
    }
}

These intersection types should function similarly to interfaces, as they can be implemented by classes and validated when assigning object literals to them.

An alternative approach using interfaces would involve a bit more verbosity and require a type query to retrieve the original type of the field, along with another intersection:

export interface DataModule extends Module {
    structure: Module['structure'] & {
        visible: boolean;
    }
}

export interface UrlModule extends Module {
    structure: Module['structure'] & {
        url: string;
    }
}

For a more verbose option (though easier to comprehend in some ways), you could define a separate interface for structure:

export interface IModuleStructure {        
    icon: string;
    label: string;
}
export interface Module {
    name: string;
    data: any;
    structure: IModuleStructure;
}
export interface IDataModuleStructure extends IModuleStructure {
    visible: boolean;
}
export interface DataModule extends Module {
    structure: IDataModuleStructure;
}
export interface IUrlModuleStructure extends IModuleStructure {
    url: string;
}
export interface UrlModule extends Module {
    structure: IUrlModuleStructure;
}
let urlModule: UrlModule = {
    name: "",
    data: {},
    structure: {
        icon: '',
        label: '',
        url: ''
    }
}

Edit

Following @jcalz's suggestion, we might also consider making the module interface generic and passing the appropriate structure interface:

export interface IModuleStructure {        
    icon: string;
    label: string;
}
export interface Module<T extends IModuleStructure = IModuleStructure> {
    name: string;
    data: any;
    structure: T;
}
export interface IDataModuleStructure extends IModuleStructure {
    visible: boolean;
}
export interface DataModule extends Module<IDataModuleStructure> {
}
export interface IUrlModuleStructure extends IModuleStructure {
    url: string;
}
export interface UrlModule extends Module<IUrlModuleStructure> {
}
let urlModule: UrlModule = { // Alternatively, we could simply use Module<IUrlModuleStructure>
    name: "",
    data: {},
    structure: {
        icon: '',
        label: '',
        url: ''
    }
}

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

I am searching for a way to retrieve the event type of a svelte on:input event in TypeScript, but unfortunately, I am unable to locate it

In my Svelte input field, I have the following code: <input {type} {placeholder} on:input={(e) => emitChange(e)} class="pl-2 w-full h-full bg-sand border border-midnight dark:bg-midnight" /> This input triggers the fo ...

Troubleshooting the Issue with Conditional Rendering in Nextjs & TypeScript

Struggling with rendering a component conditionally. I have a drawHelper variable and a function to toggle it between true and false. The component should render or not based on the initial value of drawHelper (false means it doesn't render, true mean ...

The type 'string' cannot be utilized to index type

Apologies for adding yet another question of this nature, but despite finding similar ones, I am unable to apply their solutions to my specific case. Could someone please assist me in resolving this TypeScript error? The element implicitly has an 'an ...

Mongoose and TypeScript - the _id being returned seems to be in an unfamiliar format

Experiencing unusual results when querying MongoDB (via Mongoose) from TypeScript. Defined the following two interfaces: import { Document, Types } from "mongoose"; export interface IModule extends Document { _id: Types.ObjectId; name: stri ...

Tips for Sending Variables in HTTP Requests in Angular 9

'''Is there a way to pass fromDateTime and toDateTime as parameters in this link?''' export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration { const protectedResourceMap = new Map<string, Array& ...

The addition of special characters to strings in TypeScript through JavaScript is not functioning as expected

I need assistance on conditionally appending a string based on values from captured DOM elements. When the value is empty, I want to include the special character "¬". However, when I try adding it, I get instead because the special character is not reco ...

Discovering all imported dependencies in a TypeScript project: A step-by-step guide

Currently, I am attempting to consolidate external libraries into a vendor bundle through webpack. Instead of manually listing dependencies, I would like to automate this process by scanning all TypeScript files in the directory and generating an array of ...

How can I define the type of a constructor that requires a parameter in TypeScript?

Having identified the issue, let's focus on a minimal example: // interfaces: interface ClassParameter{ x:number } interface ClassParameterNeeder{ y:number } type ClassParameterConstructor = new () => Cla ...

Using rxjs takeUntil will prevent the execution of finalize

I am implementing a countdown functionality with the following code: userClick=new Subject() resetCountdown(){this.userClick.next()} setCountDown() { let counter = 5; let tick = 1000; this.countDown = timer(0, tick) .pipe( take(cou ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Error: `__WEBPACK_IMPORTED_MODULE_1_signature_pad__` does not function as a constructor

I recently discovered the angular2-signature-pad library for capturing signatures in my Angular project. I attempted to integrate the library using the following steps: // in .module.ts file import {SignaturePadModule} from "angular2-signature-pad"; @NgMo ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

Preventing Multiple Login Attempts in Angular.js Using Typescript

Is there a way to maintain the user login attempts limit even after page refresh? login() { /* Check if user has fewer than 5 failed login attempts */ if (this.failedAttempts < 4) { this.auth.login(this.credentials).subscribe(() => { this.rou ...

Utilize TypeScript to re-export lodash modules for enhanced functionality

In my TypeScript project, I am utilizing lodash along with typings for it. Additionally, I have a private npm module containing utilities that are utilized in various projects. This module exports methods such as: export * from './src/stringStuff&apo ...

Displaying errors from an API using Angular Material mat-error

I am currently working on a form that includes an email field. Upon saving the form, the onRegisterFormSubmit function is called. Within this function, I handle errors returned by the API - specifically setting errors in the email form control and retrie ...

"Encountering a TypeScript error when using React Query's useInfiniteQuery

I am currently utilizing the pokeApi in combination with axios to retrieve data import axios from 'axios' export const fetchPokemonData = async ({ pageParam = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=20" }) => { try ...

Does having an excessive amount of variable declarations result in a noticeable decline in performance?

One thing I notice for the sake of readability is that I tend to create new variables for data that I already have on hand. I'm curious, does this impact performance significantly? Here's an example of what I mean: const isAdult = this.data.per ...

What exactly does RouteComponentProps entail?

While exploring information on React, I came across the term RouteComponentProps. For example: import { RouteComponentProps } from 'react-router-dom'; const ~~~: React.FC<RouteComponentProps> and class BookingSiteOverview extends React.Com ...

Removing data from a table using an identifier in Typescript

Recently, I have made the switch from using Javascript to TypeScript. However, I am facing an issue while trying to delete data from a table in my code. Whenever I attempt to delete data, I encounter this error message: Property 'id' does not e ...