Tips for utilizing JavaScript object destructuring to extract a specific portion of an argument while still keeping a reference to the rest of the properties in a single value

In my current project, I am exploring the possibility of using TypeScript/Javascript object destructuring to target only certain properties of an object while preserving the rest of the properties in a separate variable. I am specifically looking for a way to capture all other properties/keys that are not explicitly targeted.

The scenario I'm working on involves extending a class through inheritance while keeping the APIs similar. In the example provided below, I aim to utilize object destructuring for the properties onlyForB and alsoOnlyForB, while passing all remaining properties to the config variable.

class A {
   constructor(config) {
     this.name = config.name;
     // ...
   }
}

class B extends A {
  constructor({ onlyForB, alsoOnlyForB, ..config }) { // using ...config doesn't work
    this.onlyForB = onlyForB;
    this.alsoOnlyForB = alsoOnlyForB;
    super(config);
  }
}


const b = new B({ onlyForB: "B", alsoOnlyForB: "B2", name: "Satoshi", age: 100});
/**
 Trying to achieve the following in class B's constructor

   onlyForB -> "B"
   alsoOnlyForB -> "B2"
   config -> { name: "Satoshi", age: 100 }

*/

When attempting to implement this with

{ onlyForB, alsoOnlyForB, ..config }
which is akin to utilizing the spread syntax for object creation, errors arise. The actual use case involves extending a third-party class with numerous "config" properties and working within a TypeScript environment.

Is there a method to accomplish this task without manually removing all the object properties specific to the B class?

Side Note: To those familiar with Python, I am seeking a solution resembling the functionality of **kwargs, as seen in

def __init__(self, onlyForB, alsoOnlyForB, **kwargs)
.

Answer №1

In tackling a task like this, numerous approaches are conceivable; here is a specific example:

type ConfigForB = {
    onlyForB: string,
    alsoOnlyForB: string,
    age: number,
    name: string
}

type ConfigForA = Omit<ConfigForB, 'onlyForB' | 'alsoOnlyForB'>

class A {
   private name: string 
   constructor(config: ConfigForA) {
     this.name = config.name;
     // ...
   }
}

class B extends A {
  private onlyForB: string
  private alsoOnlyForB: string
  constructor({ onlyForB, alsoOnlyForB, ...config }: ConfigForB) {
    super(config);
    this.onlyForB = onlyForB;
    this.alsoOnlyForB = alsoOnlyForB;
  }
}

const b = new B({ onlyForB: "B", alsoOnlyForB: "B2", name: "Satoshi", age: 100});

A ConfigForB type has been defined with the specified four properties and utilized in the constructor for B. Additionally, the Omit<Type, Keys> utility type has been employed to create a new ConfigForA type that mirrors ConfigForB but lacks the onlyForB and alsoOnlyForB keys.

If explicitly described, it would appear as follows:

type ConfigForA = {
    age: number,
    name: string
}

This alternative method also functions effectively - utilizing Omit proves beneficial as it eliminates redundancy.

You can experiment with this setup on the TS Playground here.

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

Exploring the best practices for rendering nested array elements in React.js

Is there a way to display only one URL from a nested array in React using CardMedia component? https://i.sstatic.net/K6JDz.png {props.currentTodos.map((currentTodo) => ( <CardMedia className={cl ...

The issue with jqTransform not displaying the select box value on a hidden contact form

Could really use some assistance here and apologize if it's a hassle: Link to contact form To view the contact form, simply click the "Contact" button in the top left corner. The jqTransform jQuery plugin is being used to style it. Initially, it&apo ...

The functionality of json_encode seems to vary when applied to different PHP arrays, as it successfully encodes data for

My current challenge involves importing three arrays from PHP into JS using json_encode. Below is the code snippet I am currently working on: <?php $query2 = "SELECT * FROM all_data"; $result2 = $conn->query($query2); $bu = []; ...

Learn the process of retrieving JSON data in an Excel file using the json_to_sheet function

I am currently working on populating an excel file by utilizing the JSON data provided below. This JSON data is retrieved from an HTTP response and I intend to utilize it for downloading an excel file. { "dynaModel":[ { ...

Could someone clarify for me why I am unable to view the connection status within this code?

Having trouble with the Ionic Network plugin. I've included this code snippet, but it's not functioning as expected. No console logs or error messages are showing up. import { Network } from '@ionic-native/network'; ionViewDidLoad() { ...

The error message "Cannot read property 'data' of undefined" is commonly seen in Vue.js when using Axios

I am encountering an issue where the JSON data is not displaying in cards or list format after performing a search. The search functionality appears to be working as I can see the API call with the search text in the console. However, nothing is being disp ...

Passing a string array from View to Controller using Url.Action in MVC framework

I am facing an issue where I have a method that returns an array (string[]) and I am attempting to pass this array of strings into an Action. However, I am currently unable to pass my parameters as expected. Being new in MVC3, I would appreciate any insi ...

Create an elegant and responsive collapsible navigation bar with Bootstrap 4's standalone collapse JavaScript

After creating a small website using Bootstrap 4.3.1, I realized that the only JavaScript required is for the collapse plugin in the responsive navbar with a toggler button. Unfortunately, since there is no longer a customizer for Bootstrap 4, I am forced ...

How can I submit multiple dropdown menus when they are changed?

I recently added Four dropdown menus on my index.php page. <select name="filter_month" class="filters"> <option>Select a Month</option> <option value="1">January</option> <option value="2">February</optio ...

Executing code after finishing a fetch in Next.js

Here is the JavaScript code snippet under question: async function checkAuth() { console.log("3") await fetch(apiUrl+'/auth', { method: 'POST' }).then(response => response.json()).then(result => { ...

Creating Angular UI states with parameters in TypeScript

My Understanding In my experience with TypeScript and angular's ui state, I have utilized "type assertion" through the UI-Router definitely typed library. By injecting $state into my code as shown below: function myCtrl($state: ng.ui.IStateService){ ...

Activate Bootstrap button functionality with JavaScript

Hey team, I've got a Bootstrap button on my HTML page: ..... <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> ... <div class="accept-btn"> <button type="button" class="bt ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

AJAX requires manual updating by clicking on a button

I've created a chat system where two individuals can communicate with each other. An AJAX function has been implemented to update the message container every 2 seconds. However, I have noticed that the AJAX call doesn't run immediately after a u ...

What is the best way to add a sliding effect to this presentation?

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow I am attempting to create a sliding effect for image transitions instead of the typical fade in and out. However, I'm uncertain about how to approach this challenge. My concept i ...

Avoiding Socket IO from timing out when the browser page is inactive or not the focused tab on Google Chrome, Mozilla Firefox, and Safari mobile browsers

I have developed a basic chat application using socket io. The functionality is quite similar to the socket io chat official demo. However, I am facing an issue where Socket io times out on all mobile browsers when the user minimizes the page, opens anothe ...

Using the novalidate attribute in Angular 4.0.0

Since migrating to angular 4, I have encountered a peculiar issue with my template-driven form. The required attribute on the input field appears to be malfunctioning. It seems like the form has the novalidate attribute by default, preventing HTML5 validat ...

Angular object contains an unidentified property

While trying to send an object to the backend, I encountered an UnrecognizedPropertyException. Upon inspecting the object on both the frontend and backend, they appear to be identical. However, upon checking the object in the frontend console, I discovere ...

Rotating 3D cube with CSS, adjusting height during transition

I'm attempting to create a basic 2-sided cube rotation. Following the rotation, my goal is to click on one of the sides and have its height increase. However, I've run into an issue where the transition occurs from the middle instead of from the ...

Dealing with a routing issue in node.js/express involving JavaScript and CSS

I'm facing an issue. I need to set up a route from localhost.../cars to localhost../bmw/x1 On the localhost../cars page, there's a button that, when clicked, should load localhost../bmw/x1 This is the JavaScript code I have: const express = req ...