What is the best way to refresh the properties in an object?

I am working with a custom type object defined as follows:

export interface IPupilFilter {
  Fullname: string;
  Gender: string;
  ClassType: number;
  Language: number;
  Class: number;
  ClassNumber: number;
  Phone: string;
  Movement: string;
}
public requestLoadPupils: IPupilFilter = <IPupilFilter>{};

As I fill out the form, this object is populated according to the defined interface.

What is the best way to reset all the value properties and set them to null?

I have attempted the following:

this.requestLoadPupils = <IPupilFilter>{} as IPupilFilter;

While I can reset each property individually like:

this.requestLoadPupils.Gender = null;
I would prefer a more efficient method.

Answer №1

Using the Partial type in TypeScript would be the solution in this case.

public requestLoadPupils: Partial<IPupilFilter> = {};

If you want to clear the object, you can simply assign it to a new empty object like this:

this.requestLoadPupils = {};

Once you are confident that the form has been filled out completely, you can cast it back to a full IPupilFilter like so:

const pupilFilter = this.requestLoadPupils as IPupilFilter;

When you use Partial on an interface, it essentially makes all the properties optional. For example:

type PartialIPupilFilter = Partial<IPupilFilter>

Is equivalent to:

interface PartialIPupilFilter {
  Fullname?: string;
  Gender?: string;
  ClassType?: number;
  Language?: number;
  Class?: number;
  ClassNumber?: number;
  Phone?: string;
  Movement?: string;
}

All the elements are still typed, but you don't have to set them during instantiation.

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

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

When attempting to assign a 'string' type to the @Input property, I am receiving an error stating that it is not assignable to the 'PostCard Layout' type

Encountering an issue The error message 'Type 'string' is not assignable to type 'PostCard Layout'' is being displayed A parent component named page-blog.component.html is responsible for defining the class styles and passi ...

Storing basic input values for a function

I am currently working on developing a versatile method that is capable of accepting any number of parameters, while storing the input type for future use. Let's take a look at an example: const customizedFunction = <A extends any[]>(innerFunct ...

Can we categorize various types by examining the characteristics of an object?

Is it feasible with TypeScript to deduce the result below from the given data: const data = { field1: {values: ['a', 'b', 'c']}, field2: {values: ['c', 'd', 'e'], multiple: true} } const fiel ...

Is it possible to integrate a collection of libraries along with external dependencies into Vite?

Currently, I am in the process of packaging a library for npm that uses type: "module". To accomplish this, I have configured vite's library mode with the following settings: export default defineConfig({ css: { postcss: { plugin ...

Unexpected Null Object Error in TypeScript Function

Hi there! I'm new to TypeScript and encountered an 'Object may be null' error in a function. The function is meant to add two LinkedLists together, each representing numbers (with each digit as its own node), and return a new LinkedList. Can ...

How can I retrieve the /api/auth/me resource serverside using the NextJS AppRouter?

I am looking to implement app router in my Next.js project and have encountered an issue. In order for my app to function properly, I need to make a call to /api/auth/me which will return either a user object or null if the user is not logged in. To achiev ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

Issue encountered during rendering: "TypeError: Attempting to access property '_t' of an undefined object" while running a Unit Test using Jest

I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error: console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884 TypeError: Cannot read property ' ...

Deleting an element from a two-field object in TypeScript 2

I am working with a 2-field object structure that looks like this { id: number, name: string } My goal is to remove the name field from this object. How can I achieve this in TypeScript? I have attempted using methods like filter and delete, but all I r ...

Is it possible for a TypeScript definition file to include a require statement?

Can I include a statement like this in my definition file (.d.ts)? import foo = require('some-module/bar'); I believed this would automatically convert my definition file into a module. Surprisingly, it still works for me even without strict mo ...

What's the best way to add animation to the send icon while hovering over the button?

<div class="text-center"> <button [disabled]="btnStatus" class="btn btn-secondary buttonSend" type="submit"> <div [hidden]="btnStatus"> Send Message&nbsp;&nbs ...

Verify if an object property is called with the toHaveBeenCalledWith() function in Jasmine

Recently started incorporating Jasmine into my workflow and I am trying to verify if my method was called with an object that includes a MyProperty property. Currently, my setup looks like this: expect(service['method']).toHaveBeenCalledWith(jasm ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

The NestJS HttpService is encountering issues with API calls when an Interceptor is implemented

When using NestJS API App with HttpService to call another API, the functionality works successfully without any custom interceptors. However, the issue arises when attempting to view the response from the called API. The following code snippet showcases ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

Tips for incorporating JavaScript modules into non-module files

Learning how to use js modules as a beginner has been quite the challenge for me. I'm currently developing a basic web application that utilizes typescript and angular 2, both of which heavily rely on modules. The majority of my app's ts files ...

CDK Drag and Drop capability for lists within lists

I am trying to figure out how to display users and their corresponding information in a structured way. Each user should be presented in their own column, with the associated information displayed within that column. I have been attempting to drag and drop ...

Accessing environment-based constants in TypeScript beyond the scope of Cypress.env()Is there a way to gain access to environment-specific constants

Imagine I have an API test and the URL and Credentials are different between production and development environments: before("Authenticate with auth token", async () => { await spec().post(`${baseUrl}/auth`) .withBody( { ...