What is the best way to combine properties from Type1 and Type2 to create a new type in Typescript?

Here is a snippet of code I'm working with:

interface Notification {
  message: TemplatedEmail & Email, //current attempt which doesnt do what I want
}

interface Destination {
  ccAddresses?: string[],
  bccAddresses?: string[],
  toAddresses: string[]
}

interface TemplatedEmail {
  destination: Destination,
  source: string,
  template: string,
  templateData: any,
  replyToAddresses?: string[]
}

interface Email {
  destination: Destination,
  source: string,
  body: string,
  subject: string,
  replyToAddresses?: string[]
}

I am trying to ensure that the message property of Notifications can be either of type Email or TemplatedEmail. This means that all properties (optional ones too) of either Email should be present in message, or all properties of TemplatedEmail. With Union Types, I can only access common properties, and with intersection types, I get all properties from both.

The issue arises when trying something like this:

const x: Notification = { 
    message: {
          destination: { toAddresses: [ "" ] },
          source: "",
          body: "",
          subject: ""
    }
};

This causes an error indicating that the properties template and templateData are missing from x.

Answer №1

If you want to maintain the structure of your message while achieving a similar outcome, consider implementing a discriminated union:

type MessageType = Announcement | Reminder;

interface Announcement {
  type: 'announcement',
  content: PromoEmail
}

interface Reminder {
  type: 'reminder',
  content: ReminderEmail
}

const message: MessageType = { 
    type: 'announcement',
    content: {
          recipient: { emailAddresses: [ "" ] },
          sender: "",
          body: "",
          subject: ""
    }
};

For a live example showcasing this approach, check out this playground 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

Greetings, Angular2 application with TypeScript that showcases the beauty of the world

I've been working on my first angular2 program and noticed some deviations from the expected output. typings.json: { "ambientDependencies": { "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f ...

Changing the button class during an event in Angular 4

In the process of creating an MCQ test, I am looking to implement a feature where selected button options are highlighted in green upon clicking. While I have successfully implemented this feature using Angular 1, I am facing challenges in converting it to ...

Discover the method of extracting information from an object and utilizing it to populate a linechart component

Object Name: Upon calling this.state.lineChartData, an object is returned (refer to the image attached). The structure of the data object is as follows: data: (5) [{…}, {…}, {…}, {…}, {…}, datasets: Array(0), labels: Array(0)] In the image p ...

What is the best way to refresh the snapshots in my React/TypeScript project?

I am working on a React/TypeScript project that utilizes the Jest testing framework. Occasionally, after making changes to my code, Jest will compare it to the snapshots and generate an alert requesting me to update them. However, there are instances where ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Handling JSON data with Reactive Extensions in JavaScript

Hey everyone, I'm a beginner in Angular and RxJS coming from a background in VueJS. I've been struggling to grasp the inner workings of RxJS and would really benefit from some guidance from more experienced individuals regarding my current issue. ...

Jasmine has detected an undefined dependency

Testing out the following code: constructor(drawingService: DrawingService) { super(drawingService); //... } private writeOnCanvas(): void { this.drawingService.clearCanvas(this.drawingService.previewCtx); this.drawing ...

Enhance your FullCalendar experience with React by displaying extra information on your calendar

I am new to using React and FullCalendar, and I have a page layout similar to the image linked below. Additionally, I have a list of events structured as shown: id: "9", eventId: "1", title: "Training Network", st ...

Handling HTTP Errors in Angular Components with NGRX

I have successfully integrated the store into my angular project. I am able to handle and process the successSelector, but I am facing difficulty in capturing any data with the errorSelector when an HTTP error occurs from the backend. The error is being c ...

How to Incorporate and Utilize Untyped Leaflet JavaScript Plugin with TypeScript 2 in Angular 2 Application

I have successfully integrated the LeafletJS library into my Angular 2 application by including the type definition (leaflet.d.ts) and the leaflet node module. However, I am facing an issue while trying to import a plugin for the Leaflet library called "le ...

Altering the parent component's output depending on a boolean value established in the child component within Angular

Recently I began learning Angular and find myself in need of some assistance when it comes to managing a specific situation with Angular 16. In our project, we have two different versions of the site header represented by two components - one as the defaul ...

Develop a TypeScript Module that consolidates all exports

My Goal with TypeScript Modules I aim to streamline my TypeScript project by creating a module that contains all the necessary class exports. Currently, I find myself using relative import statements in my classes, which can make maintenance challenging i ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

Issues with the functionality of Angular Firebase Authentication Service

I am currently working on setting up an authentication service in Angular that will integrate with Google Firebase for a Login form. However, I have encountered an issue where including the service in the constructor of my LoginComponent prevents me from a ...

The module located at "c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx" does not have a default export available

I am currently delving into the realm of RxJs. Even after installing rxjs in package.json, why am I still encountering an error that says [ts] Module '"c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx"' has no default export ...

Error encountered while attempting to load SWC binary for win32/ia32 in a Next JS application

Upon installing a Next.js app using the command npx create-next-app@latest, I encountered an error while running the app. Can anyone explain why this error occurred and provide a solution? PS D:\New folder\my-app> npm run dev [email pr ...

Unable to modify the theme provider in Styled Components

Currently, I am attempting to customize the interface of the PancakeSwap exchange by forking it from GitHub. However, I have encountered difficulties in modifying not only the header nav panel but also around 80% of the other React TypeScript components. ...

What is the process for importing a TypeScript module exclusively through typings without having to download it separately?

Currently, I am working on a widget for a website that is already utilizing jQuery and I am using TypeScript. The goal is to embed my output into the host website while taking advantage of the existing jQuery library loaded by the host site. In order to r ...

Enhancing the session object with new properties

I am attempting to include extra properties in the session object req.session.confirmationCode = confirmationCode; However, I encounter an error stating that the property confirmationCode does not exist Property 'confirmationCode' does not exist ...

Creating Concurrent Svelte Applications with Local State Management

Note: Self-answer provided. There are three primary methods in Svelte for passing data between components: 1. Utilizing Props This involves passing data from a parent component to a child component. Data transfer is one-way only. Data can only be passed ...