What is the method in TypeScript to expand an object using __proto__?

My current code is not working as expected:

export function extendObject<
  T extends Object,
  X extends Object,
>(x: T, a: X): T & X {
  const p = { __proto__: x }
  Object.assign(p, a)
  return p
}

However, I am encountering an error when I reach the return p part:

Type '{ __proto__: T; }' is not assignable to type 'T & X'.
  Type '{ __proto__: T; }' is not assignable to type 'T'.
    '{ __proto__: T; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Object'.ts(2322)

Originally, the code was in JavaScript and looked like this:

export function extendObject(x, a) {
  const p = { __proto__: x }
  Object.assign(p, a)
  return p
}

Here is how I would use it in JavaScript:

const a = { foo: 'bar' }
const b = extendObject(a, { one: 2 })
assert(b.foo === 'bar')
assert(b.one === 2)

I am struggling to properly type this in TypeScript to make it compile. I would prefer to use __proto__ for performance reasons, but if that's not feasible, how else can I achieve a similar outcome?

I also attempted a different approach, but it didn't work:

export function extendObject<
  T extends Object,
  X extends Object,
>(x: T, a: X): T & X {
  const p: T & X = {}
  Object.keys(x).forEach(key => (p[key] = x[key]))
  Object.keys(a).forEach(key => (p[key] = a[key]))
  // Object.assign(p, a)
  return p
}

Answer №1

Have you attempted to utilize object destructuring?

export function combineObjects<
  A extends Object,
  B extends Object,
>(a: A, b: B): A & B {
  const c = { ...a, ...b }
  return c
}

It is important to keep in mind that this function does not perform a deep clone. Any references present in a and b will only be shallow copied.

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

What is the reason for TypeScript allowing this promise chain without any compilation errors?

Although I am still relatively new to Typescript, I find myself grappling with a particular issue that has been perplexing me. I am unsure why the following code snippet triggers a compilation error: // An example without Promises (does not compile) funct ...

Is there a way to showcase the contents of the angular "tags" object seamlessly?

Is there a way to show the content of the "tags" object using angular? I attempted to achieve it using {{gallery.tags.tag}} but unfortunately, it did not work import {IPhoto} from "./iphoto"; export interface IGallery { galleryId: string; title: ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

Discover the power of catching Custom DOM Events in Angular

When working with an Angular library, I encountered a situation where a component within the library dispatches CustomEvents using code like the following: const domEvent = new CustomEvent('unselect', { bubbles: true }); this.elementRef.nati ...

Encountering an issue with managing promises in Observables for Angular HTTP Interceptor

Currently, I am encountering the following situation: I have developed an authentication service using Angular/Fire with Firebase authentication. The authentication service is expected to return the ID token through the idToken observable from Angular/Fir ...

A guide to integrating a component into another component in Angular

Currently, I am encountering an issue with importing a component into another in my Ionic 5.0.0 application. Within my application, I have two separate modules: ChatPageModule and HomePageModule. My objective is to include the Chat template within the Hom ...

Encountering a problem with the chipGrid feature in Angular Material version

I am currently facing an issue with my angular material chip component. The versions I am using are Angular 16 and Material 16. Here are all my dependencies: "@angular/animations": "^16.0.4", "@angular/cdk": "^16.0.4&quo ...

What is the best way to dynamically set an ID in Angular using the pound symbol (#)?

I am currently developing a dynamic Angular 6 application that utilizes dynamic components. My approach involves using @ViewChild('<id>', { read: ViewContainerRef }) <id>; to reference the divs where I intend to populate with dynamic ...

Challenges with importing and using jspdf and autotable-jspdf in Angular 8

Issue with Generating PDF Using Angular 8, JSPDF, and JSPDF-AutoTable I am facing a challenge with exporting/generating a PDF based on an HTML grid. I need to make some DOM changes with CSS, remove toggle buttons, alter the header, etc. However, all the s ...

In my current project, I am working with Knockout and TypeScript but I am encountering difficulties in firing the window-resize event

Instead of using jquery, I prefer working with a custom handler for the $(window).resize(function () { ... event. If there is a way to achieve this without relying on jquery, please feel free to share it in the comments below. The code snippet below show ...

Determine the difference between dates using Angular 2's array filtering function

Here's a way to get the current time in seconds: let currentTimeInSeconds = new Date().getTime() / 1000; I have an array containing objects with an expirationDate property that returns expiration time in seconds. I can find the bills that have expir ...

Enforcing the requirement of null values

My goal is to create a variable that can either hold a number or be null. The purpose of this variability is to reset the variable at times by setting it to null. However, I am facing an issue where if I declare the variable with the type number | null, I ...

I'm curious about the significance of this in Angular. Can you clarify what type of data this is referring

Can anyone explain the meaning of this specific type declaration? type newtype = (state: EntityState<IEntities>) => IEntities[]; ...

Modify the MUI time picker to display as a digital clock inside a DateTimePicker widget

I need to update my MUI DateTimePicker component to use the DigitalClock time picker instead of the Analog Clock picker. The current component has two steps, first picking the date from a calendar and then selecting the time. This change is only necessary ...

Universal categories, limitations, and hereditary traits

As a newcomer to Typescript and generics, I am unsure if I have encountered a bug/limitation of Typescript or if I am missing the correct approach to achieve my desired outcome. I have a base class called Widget which is generic and holds a value of type ...

Record the variable as star symbols in the VSTS Extension

I am working on a VSTS extension using Typescript and utilizing the vsts-task-lib Currently, I am encountering an issue with the execSync function, which displays the command being executed. However, I need to hide a token obtained from a service by displ ...

The sticky navbar fails to stay in place when the content becomes too lengthy

This is my current state of code (minified, for explanation only) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-w ...

The historical state pushed through history is not accessible in the redirected class

Having a scenario where I need to redirect from one page to another and pass the state as a prop to the redirected page. I've utilized history.push and attempted to access it using console.log(this.props.location.state.searchString) but encountering a ...

What is the method for importing the merge function from "lodash/merge" in TypeScript?

When using ES6, it's possible to import only a single function from a library in order to reduce the overall bundle size. For example: import merge from "lodash/merge" But in TypeScript, the statement above can trigger a compile error: Cannot find m ...