Eliminate attributes from an object that are not defined within a specific type interface

I am trying to filter out properties from an object that are not defined in a specific type interface.

Suppose I have the following interface:

export interface CreateCustomerUserInput {
    fullname: string;
    email: string;
}

And this is my initial object:

let obj = {fullname: 'AAA', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e5e5c4e5e5aae7ebe9">[email protected]</a>', phone: '111', address: 'XXX'};

What I want is to create a new object with only the properties declared in the type interface. Here is the expected result:

let c = {fullname: 'AAA', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8c8cad8c8cc38e8280">[email protected]</a>'}

Is there an efficient way to achieve this in TypeScript?

Answer №1

If I'm understanding your request correctly, you're looking to remove any properties from an object that are not defined in a specific type interface.

Unfortunately, during runtime, type interfaces are not accessible - meaning they do not exist when the JavaScript code is executed. As a result, there is no way to programmatically access reflective information about the type.

However, one potential solution could be utilizing a class. For instance, let's say you have the following class:

export class CreateCustomerUserInput {
    public fullname: string = "";
    public email: string = "";
}

You could instantiate this class and loop through its properties using a for.. in loop or with Object.keys(). Then, by using delete, you could remove any properties from your object that are not present in the class instance.

To make this approach effective, ensure that all properties of the class are initialized after construction.

Another option involves using TypeScript decorators with the experimental metadata flag, as detailed here: http://www.typescriptlang.org/docs/handbook/decorators.html.

These decorators retain reflective information, but solely for classes (or abstract classes)!

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

The integration of cypress-cucumber-preprocessor with multiple testing frameworks appears to be experiencing compatibility issues

I am trying to set up a connection between Cypress and Cucumber, and I came across this plugin: https://www.npmjs.com/package/cypress-cucumber-preprocessor However, I am having trouble with my implementation as it seems to be missing. I have also added th ...

Is it correct to implement an interface with a constructor in TypeScript using this method?

I am completely new to TypeScript (and JavaScript for the most part). I recently came across the article discussing the differences between the static and instance sides of classes in the TypeScript handbook. It suggested separating the constructor into an ...

Loop through every item in Typescript

I am currently working with the following data structure: product: { id: "id1", title: "ProductName 1", additionalDetails: { o1: { id: "pp1", label: "Text", content: [{ id: "ppp1", label: "Tetetet" ...

Implementing express-openid-connect in a TypeScript project

Trying to incorporate the express-openid-connect library for authentication backend setup with a "simple configuration," an issue arises when attempting to access the oidc object from express.Request: app.get("/", (req: express.Request, res: express.Respon ...

Giving the function parameter dynamic type depending on the first parameter

Currently, I have a basic function that my client uses to communicate with my server. In order to maintain flexibility, I have implemented the following: public call(method: string, ...parameters: any[]) {} On the server side, I organize all methods toge ...

The services generated by OpenAPI Generator typescript-angular are experiencing failures

While utilizing version 2.4.26 of this OpenApi generator ("@openapitools/openapi-generator-cli": "^2.4.26"), I am encountering issues with Angular services (Angular Version 13.2.0). For example, the services are passing too many arguments to the Angular Ht ...

Challenging Issue: "The 'any' type cannot be assigned to the 'never' type"

Currently facing a challenging Typescript problem that has me puzzled. The issue arises at the line themeToChange[tileId][key] = value; The error message states Type 'any' is not assignable to type 'never' This error is directly rela ...

Tips for utilizing MUI Typography properties in version 5

I'm clear on what needs to be done: obtain the type definition for Typography.variant. However, I'm a bit uncertain on how to actually get these. interface TextProps { variant?: string component?: string onClick?: (event: React.MouseEvent&l ...

TypeScript combined with Vue 3: Uncaught ReferenceError - variable has not been declared

At the start of my <script>, I define a variable with type any. Later on, within the same script, I reference this variable in one of my methods. Strangely, although my IDE does not raise any complaints, a runtime error occurs in my console: Referenc ...

Combine two arrays into one

When attempting to combine two arrays, the result looks like the image linked below: https://i.sstatic.net/3FWMZ.png I want the merged array to resemble the following example: {0: {…}, storedArr: Array(2)} 0: address: "ifanio de los Santos Ave, Ma ...

When a user clicks on empty space in Angular 2, the page will automatically redirect

When I receive a response from the server, I want to redirect to another page. However, this process takes around 60 seconds, so in the meantime, I want to display a spinner. Once the response is received, I should be redirected to the new page. Sounds sim ...

Transform current JSON data into formatted JSON format using JavaScript or TypeScript

I have a JSON structure that needs to be reformatted in order to meet the requirements of an external service. Although the current format is complex and cannot be altered, I need to modify it to match the desired output for the external service. Current ...

Executing a series of asynchronous HTTP calls in Angular until a specific condition is satisfied

In Angular, I am making an HTTP call that returns a promise. Currently, I am refreshing the call using setTimeout at regular intervals. Are there any built-in functions or design patterns available to handle this task more efficiently? ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

What is the best way to display various tables depending on the grouping of a specific row value?

Recently, I came across some interesting JSON data that looks like this: [ { "fruit":"apple", "country": "A" }, { "fruit":"banana", "country": "b" }, { "fruit":&q ...

Oops! Angular2 couldn't find a provider for HttpHandler

I have been working on implementing HttpCache through an interceptor. Below is the code snippet for caching-interceptor.service.ts: import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http' import ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

Issue with dispatching actions in React using TypeScript and hooks

Can you please point out what I'm doing wrong here: I am encountering the following error Type '{ wishList: any; addBookToWishList: (book: any) => void; }' is not assignable to type '{ wishList: never[]; }'. Object literal may ...

`Getting Started with TypeScript in an ASP.Net MVC Application`

Due to certain reasons, we have decided to begin our project with TS rather than JS. We are facing issues with the variables set in the MVC Views, which are established by the Model of each View. For example, tes.cshtml: @model Testmodel <script> ...

Can type safety be ensured for generic abstract methods without the use of superclass generics?

I am currently dealing with a situation where I have an abstract class that contains generic types for internal purposes only: public abstract class ParentClass<T, U> { // Some common code to prevent code duplication in child classes protect ...