typescript, generate a new type by merging option values

In typescript I am faced with a challenge. I have a type called A:

interface A {
    a1: string;
    a2: int;
}

As well as another type called B:

interface B {
    b1: number
}

Now, my goal is to create a new type:

interface AB {
    a1?: string;
    a2?: string;
    b1: string;
}

This new type should combine all optional values from type A with type B. How can I achieve this in typescript?

Answer №1

This question was previously addressed at: Merge Two Interfaces, with the main distinction being the utilization of the Partial function which constructs a type with all properties of Type set to optional. This utility generates a type that includes all subsets of a given type.:

You have the option to either define a new interface:

interface Ci extends Partial<A>, B {}

or create a type:

type Ct = Partial<A> & B

You can test this out on the TypeScript playground with the following code:

interface A {
  a1: string
  a2: number
}

interface B {
  b1: number
}

interface Ci extends Partial<A>, B {}

type Ct = Partial<A> & B

const interfaceType: Ci = {a1: 'blah', a2: 1, b1: 2}

const typeType: Ct = {a1: 'blah', a2: 1, b1: 2}

const partialInterfaceType: Ci = {b1: 1}

const partialTypeType: Ct = {b1: 1}

console.log('interfaceType', interfaceType)
console.log('typeType', typeType)
console.log('partialInterfaceType', partialInterfaceType)
console.log('partialTypeType', partialTypeType)

Check it out on the TypeScript playground by clicking on this link: Playground

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

Form for creating and updating users with a variety of input options, powered by Angular 2+

As I work on creating a form, I encounter the need to distinguish between two scenarios. If the user selects 'create a user', the password inputs should be displayed. On the other hand, if the user chooses to edit a user, then the password inputs ...

A reflective key error has occurred because the token was not properly defined!

My current setup includes Angular version 2.4.4. However, I encountered an issue when trying to declare a service resolver and register it in both the component module and router. import { Injectable } from '@angular/core'; import { Resolve, Ac ...

Examining the array to ensure the object exists before making any updates in the redux

Is there a way to determine if an object exists in an array and update it accordingly? I attempted to use the find method, but it couldn't locate the specified object. I also tried includes, but it seems to be unable to recognize the item within the ...

Ionic app experiencing a CORS dilemma post-build

Using Ionic 3, I have written a provider code to fetch data from an API endpoint hosted on an HTTPS server. For example, my endpoint is located at . Below is the code for my provider: // Provider Class Function load(){ if(this.data){ return Pro ...

Assigning dynamic key value pairs in Angular 4 using Typescript

I'm currently attempting to construct an object using keys that are specified in an environment file, meaning the keys would vary depending on the environment. import { environment } from '../environments/environment' export abstract class ...

Proper method for determining return type through the use of `infer`

I need to find out the return type based on input values, like in the code below: type ReturnType<S> = { array: S extends 'number' ? number[] : S extends 'string' ? string[] : never; value: S extends 'number' ? n ...

VIDEOJS ERROR: A peculiar mistake has occurred. TypeError: The property 'value' cannot be read since it is undefined in the context of

Recently, I came across a fascinating plugin called videojs-thumbnails for video.js, and I'm eager to incorporate it into my angular component. However, I keep encountering an error that says: VIDEOJS: ERROR: TypeError: Cannot read property 'val ...

Issue connecting database with error when combining TypeORM with Next.js

I am attempting to use TypeORM with the next.js framework. Here is my connection setup: const create = () => { // @ts-ignore return createConnection({ ...config }); }; export const getDatabaseConnection = async () => { conso ...

Type definition for Vuex store functionality

Working on creating a versatile type to provide typing hints for mutations in Vuex. After reading an inspiring article on Vuex + TypeScript, I decided to develop something more generic. Here is what I came up with: export type MutationType<S, P, K exten ...

Mapbox GL JS stops displaying layers once a specific zoom level or distance threshold is reached

My map is using mapbox-gl and consists of only two layers: a marker and a circle that is centered on a specific point. The distance is dynamic, based on a predefined distance in meters. The issue I'm facing is that as I zoom in and move away from the ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

Is it possible to prevent casting to any by improving type definitions?

My query can be best elucidated with the following code snippet. The comments within the code aim to provide clarity on the nature of the question. type MediaFormats = "video" | "audio"; type IMediaContent<TType extends MediaFormats, TValue> = { ...

Poorly packaged library - Custom Angular library - Node Package Manager

Recently, I've been delving into the process of publishing a simple Angular library on NPM. Despite following various tutorials (like those found here, here, and here), I faced difficulties when attempting to use it in a test project. MY JOURNEY In s ...

The modification in Typescript's type order from version 1.7 to 1.8 resulted in a significant

A Visual Studio Cordova application with a unique TypeScript source structure: /src /app /appsub1 appsub1.ts -> 4 : 7 /appsub2 appsub2.ts -> 5 : 6 app.ts -> 3 : 5 /mod1 /mod1sub1 mod1sub1.ts -> 7 : 4 m ...

When changing the dropdown option on a separate page in React/Next JS, all checkboxes show the clicked style as a result of utilizing useState

I have implemented checkboxes for three different categories: "Types", "Price", and "Categories". They function correctly, with data being passed to a separate checkbox component without any issues. The problem arises when I click a checkbox and then inte ...

What is the best way to showcase a view on the same page after clicking on a link/button in Angular?

Is there a way to show a view on the same page in an Angular application when a link is clicked? Rather than opening a new page, I want it displayed alongside the list component. How can this be accomplished? Here's an illustration of my goal: I&apos ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

Using TypeScript to specify the return type of a non-mutating extension function from an external module

Imagine utilizing an external package named "foo". This package's primary export is an object containing an .extend() method that enables functionality addition by generating a derived object (while leaving the original untouched). The process typical ...

Having trouble retrieving an object property in HTML or TypeScript within an Angular framework?

export class ComponentOne { array_all_items: Array<{ page_details: any }> = []; array_page_details: Array<{ identifier: number, title: string }> = []; initial_item: Array<{ identifier: number, title: string }> = [ { ...

My type is slipping away with Typescript and text conversion to lowercase

Here is a simplified version of the issue I'm facing: const demo = { aaa: 'aaa', bbb: 'bbb', } const input = 'AAA' console.log(demo[input.toLowerCase()]) Playground While plain JS works fine by converting &apo ...