Refine current attributes of an object in Typescript

In typescript, I have an object of type any that needs to be reshaped to align with a specific interface.

I am looking for a solution to create a new object that removes any properties not defined in the interface and adds any missing properties.

An example code snippet is provided below:

interface ImyInterface {
  a: string;
  b: string;
  c?:string;
};

let myObject = {
  a: "myString",
  d: "other value"
};

My query is: Is there a method to filter and convert the myObject so that it adheres to the structure outlined in the ImyInterface interface, resulting in:

console.log (JSON.stringify(objectA));
> {a: 'myString', b: null}

Answer №1

While there could potentially be an alternative approach, here is a solution that comes to mind:

    let defaultObj: ICustomInterface = { a: null, b: null };
    let newObj: ICustomInterface = { ...defaultObj, ...customObj };

The initial line creates an object that adheres to the specified interface.

Subsequently, a new object is defined based on the desired interface and includes all properties from defaultObj, followed by any relevant properties from customObj.

IMPORTANT: Attempting to use only this code snippet:

let newObj: ICustomInterface = { ...customObj };

Would result in an error indicating missing interface properties. This emphasizes the necessity of first creating a "complete" object (defaultObj in this instance).

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

Observable<Any> Filter

I am currently utilizing Typescript and Angular 4 in my work. Within my project, I have two lists implemented using rxjs/Rx. ... myList: Observable<MyClass[]>; filteredList: Observable<MyClass[]>; ... My objective is to filter the myList base ...

Can you tell me the specific name of the HTML document style that features two columns?

Here are two websites that showcase a unique two-column style layout: http://momentjs.com/docs/ I find these sites visually appealing and I am curious about the specific name of this style. Is there a template or tool available to create documents with a ...

React developers are struggling with parsing XML data with ReactDOM

While working on my React application, I encountered an issue with parsing an XML file. When I hard code the XML data in my file listener, I get the correct answer (2): const raw = `<?xml version="1.0" encoding="ISO-8859-1" ?> <?xml-stylesheet ...

Is tsconfig.json Utilized by Gatsby When Using Typescript?

Many blog posts and the example on Gatsby JS's website demonstrate the use of a tsconfig.json file alongside the gatsby-plugin-typescript for TypeScript support in Gatsby. However, it seems like the tsconfig.json file is not actually utilized for conf ...

Tips for parsing CSV files using d3 version 4

I'm currently grappling with the documentation for CSV Parse in D3. My code snippet looks like this: d3.parse("data.csv",function(data){ salesData = data; }); Unfortunately, I keep encountering this error: Uncaught TypeError: d3.parse is n ...

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

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 ...

Place information from an input field into a specific row within a table

Utilizing Angular 4, I am developing a frontend application for a specific project. The interface features a table with three rows that need to be filled with data from an external source. https://i.stack.imgur.com/Dg576.png Upon clicking the "aggiungi p ...

What strategies can I use to ensure that I can successfully send 3,000 requests to the Google Drive API using node.js without surpassing

I'm currently assisting a friend with a unique project he has in mind. He is looking to create 3000 folders on Google Drive, each paired with a QR code linking to its URL. The plan is to populate each folder with photos taken by event attendees, who ...

How to rename a class of an image tag using jQuery

I need to update the class name in my image tag <img src="img/nex2.jpeg" class="name"> When hovering over with jquery, I want to add a new class to it. After hovering, the tag should appear as follows: <img src="img/nex2.jpeg" class="name seco ...

Is it possible to modify only the text following the bold HTML tag?

Having trouble replacing both occurrences of "a Runner" with "a Team Captain" <form id="thisForm"> <table> <tr bgcolor="#eeeeee"> <td valign="top" colspan="4" style="vertical-align: top;"> &l ...

Choose an option from a list of items in a nested array by

I'm working with a nested array (3d) and I want to populate a drop-down select menu with its values using PHP and jQuery I've tried implementing this for two-level arrays like categories and sub-categories, but what if some sub-categories have f ...

Compilation issues in node-modules arise following the Vue package and i18next updates

Recently, I decided to upgrade from the i18n package to the newer version called i18next in my project. However, this update led to numerous errors popping up during compilation. Fortunately, by adding 'skipLibCheck' to the compiler options in th ...

Learn how to display each element in a list one by one with a three-second interval and animated transitions in React

Let's consider a scenario where we have a component called List: import React, { Component } from 'react'; class List extends Component { constructor() { super(); this.state = { list: [1, 2, 3, 5] } ...

AngularJS initiates an XMLHttpRequest (XHR) request before each routeChange, without being dependent on the controller being used

I'm currently embarking on a new project, and for the initial phase, I want to verify if the user has an active session with the server by sending an XHR HEAD request to /api/me. My objective is to implement the following syntax $rootScope.$on("$rou ...

Methods for ensuring that fake browser tab focus remains on several tabs simultaneously

Is there a way to simulate multiple tab/window focus in a browser for testing purposes? I need to test pages that require user input and focus on active windows/tabs. Are there any different browsers, plugins, or JavaScript code that can help me achieve th ...

Error encountered in my application due to Node.js (Error [ERR_HTTP_HEADERS_SENT]: Unable to change headers once they have been sent to the client)

Experiencing an error message in my application when typing nodeJS. Please assist. , Encountering an error after sending the first POST request while running the app. const express = require('express') const Workout = require("../models/work ...

How can you display or list the props of a React component alongside its documentation on the same page using TypeDoc?

/** * Definition of properties for the Component */ export interface ComponentProps { /** * Name of something */ name: string, /** * Action that occurs when component is clicked */ onClick: () => void } /** * @category Componen ...

Update the content inside a <p> tag dynamically using Javascript based on the selected option

Struggling with Javascript and need some guidance. I have a select box with 4 options, and I want to update the contents of a <p> tag with an id of pricedesc based on the selected option. Here is my current code: function priceText(sel) { var l ...

Struggling with implementing Angular and TypeScript in this particular method

I'm dealing with a code snippet that looks like this: myMethod(data: any, layerId: string, dataSubstrings): void { someObject.on('click', function(e) { this.api.getSomething(a).subscribe((result: any) => { // ERROR CALL 1. It ...