Guide to making a Typescript interface by combining elements from two separate interfaces without utilizing inheritance

Programming Language: Typescript
I am looking to combine the properties of two interfaces as the value of an indexable-type within a third interface.

Interface 1:

export interface Employee {
    id: string
    name: string
}

Interface 2:

export interface Department {
    department: string
}

My goal is to define an interface that mirrors this structure:

export interface EmployeeDetails {
  employees: {
    [key: string]: {
      employeeDetails: EmployeeWithDepartment
    }
  }
}

In this case, EmployeeWithDepartment includes:

export interface EmployeeWithDepartment extends Employee {
    departmentDetails: Department
}

Is there a method to construct the EmployeeDetails interface without explicitly defining EmployeeWithDepartment? Is there a way to link both Employee and Department directly in the EmployeeDetails interface?

PS: I am fairly new to JS & TypeScript, so any advice or alternative approaches are welcome!

Answer №1

It seems like what you need is a type intersection, which involves using the & operator to combine all properties of two types.

For instance:

interface A { a: number }
interface B = { b: string }
type C = A & B // { a: number, b: string }

To implement this in your types, you could do something similar to this:

export interface EmployeeDetails {
  employees: {
    [key: string]: {
      employeeDetails: Employee & { departmentDetails: Department }
    }
  }
}

Playground


You may find this page helpful: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces

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

Include an element in a secondary list based on its position in the initial list

Having 2 lists presents a challenge. An Angular service is utilized with a splice-based method to remove items from the first list (named "items") according to their index through a ng-click action. service.removeItem = function (itemIndex) { items ...

Unable to deploy Azure App Service due to difficulties installing node modules

My Azure Node.js App Service was created using a tutorial and further customization. The app is contained within one file: var http = require("http"); //var mongoClient = require("mongodb").MongoClient; // !!!THIS LINE!!! var server = http.createServer(f ...

How can I prevent receiving redundant data and effectively manage my data?

I am currently working on adding offline support to my app. The logic I am following is to first check if there is cached feed data available. If the data is present, it will set the feeds to that cached data and display it from the cache. However, it will ...

Receiving 'Module not found' error in Typings on specific machines within the same project. Any suggestions on how to troubleshoot this issue?

I have a project cloned on two separate machines, each running VS2015 with Typings 1.8.6 installed. One machine is running the Enterprise version while the other has the Professional version, although I don't think that should make a difference. Inte ...

Ensuring consistency between TypeScript .d.ts and .js files

When working with these definitions: https://github.com/borisyankov/DefinitelyTyped If I am using angularJS 1.3.14, how can I be certain that there is a correct definition for that specific version of Angular? How can I ensure that the DefinitelyTyped *. ...

NodeJS error message: "The callback provided is not a function

As someone new to the world of NodeJS, I'm facing challenges in understanding how to pass variables and objects between functions. Any help on what I might be doing wrong would be greatly appreciated. Let's take a look at this code snippet: Inc ...

Nested data selection in React

I have been experimenting with creating a nested select optgroup and attempted the following: const data = [ { sectorId: 5, sectorName: "Sector One", departments: [ { deptName: "Production", jobtitles: [ { ...

Sending a concealed input according to the chosen option

I'm attempting to send some hidden values to a Servlet via a form, but my goal is to only pass them if the user chooses a specific option. <!-- FORM ABOVE --> <input type="hidden" name="foo" id="foo" value="foo"> <input type="hidden ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Exploring sagas: Faking a response using a call effect

In my current scenario, I am facing a challenging situation: export function* getPosts() { try { const response = yield call(apiCall); yield put({ type: "API_CALL_SUCCESS", response }); } catch(e) { // ... } Furthermore, there is a spec ...

Having trouble navigating through multiple layers of nested array data in react js

I need help understanding how to efficiently map multiple nested arrays of data in a React component and then display them in a table. The table should present the following details from each collection: title, location, description, and keywords. Below ...

What is the best way to target a specific item in a list using JavaScript in order to modify its appearance?

How can I modify the appearance of a specific li element when it is clicked? ...

What is the process for creating a unique Vee-Validate rule in TypeScript?

I am in the process of developing a unique VeeValidate rule for my VueJS component written in TypeScript. This rule is designed to validate two fields simultaneously, following the guidelines outlined in VeeValidate - Cross Field Validation. Here is a snip ...

Restrict the quantity of recommendations provided by the AutoComplete feature

After exploring the autocomplete API from https://material-ui.com/api/autocomplete/, I am unable to figure out a way, given my basic understanding of javascript, to restrict the display of a specific number of options beneath the TextField. I am working o ...

SystemJS TypeScript Project

I am embarking on a journey to initiate a new TypeScript project. My aim is to keep it simple and lightweight without unnecessary complexities, while ensuring the following: - Utilize npm - Implement TypeScript - Include import statements like: import ...

Transforming Arrays of Objects into a Single Object (Using ES6 Syntax)

My attempt to create aesthetically pleasing Objects of arrays resulted in something unexpected. { "label": [ "Instagram" ], "value": [ "@username" ] } How can I transform it into the d ...

What is the method for retrieving embedded JavaScript content?

In an attempt to scrape a website using Cheerio, I am facing the challenge of accessing dynamic content that is not present in the HTML but within a JS object (even after trying options like window and document). Here's my code snippet: let axios = ...

What is the best way to toggle the enablement of a textbox with jQuery?

Welcome all! Initially, all controls are disabled. Upon clicking the Add or New button, I want to enable textboxes and the Save button while keeping the Edit and Delete buttons disabled. Once the Save button is clicked, I wish to disable all textboxes and ...

Following the build in Angular, it only displays the index.html file and a blank screen

According to the information on Angular's official website, running the "ng build" command should generate files in the dist folder ready for hosting. However, after running this command, the index.html file is empty except for the page title. When yo ...

The Angular framework may have trouble detecting changes made from global window functions

While working, I came across a very peculiar behavior. Here is the link to a similar issue: stackblitz In the index.html file, I triggered a click event. function createClause(event) { Office.context.document.getSelectedDataAsync( Office.Coerci ...