Mixing a static class factory method with an instance method: a guide

After introducing an instance method addField in the code snippet below, I encountered an issue with the Typescript compiler flagging errors related to the static factory methods withError and withSuccess:

The error message states: 'Property 'addField' is missing in type '{ isSuccess: true; ... }' but required in type 'WebError'.

export class WebError {
    isSuccess: boolean; 
    errTitle: string;
    errSummary: string;
    errFields: WebErrorField[];
    constructor() {
            this.errFields = [];
    }
    static withError(errTitle: string = "Unknown Error", errSummary: string = "Unknown Error"): WebError {
            return { isSuccess: false, errFields: [], errTitle: errTitle, errSummary: errSummary };
    }
    static withSuccess(errTitle: string = "", errSummary: string = ""): WebError {
            return { isSuccess: true, errFields: [], errTitle: errTitle, errSummary: errSummary };
    }
    addField(fieldName: string, fieldError: string) {
            this.errFields.push({ fieldName: fieldName, fieldError: fieldError });
    }
}

How can I resolve this issue?

Answer №1

The reason why withError() and withSuccess() return a WebError is because the addField() method belongs to the WebError class, but the object returned by these static methods does not include it. To resolve this issue, you should modify the static methods to return an actual instance of WebError, instead of merely satisfying its interface with an object.

export class WebError {
  isSuccess: boolean;
  errTitle: string;
  errSummary: string;
  errFields: WebErrorField[] = [];

  constructor(params: {
    isSuccess: boolean;
    errTitle: string;
    errSummary: string;
  }) {
    this.isSuccess = params.isSuccess;
    this.errTitle = params.errTitle;
    this.errSummary = params.errSummary;
  }

  static withError(
    errTitle: string = 'Unknown Error',
    errSummary: string = 'Unknown Error',
  ): WebError {
    return new WebError({isSuccess: false, errTitle, errSummary});
  }

  static withSuccess(errTitle: string = '', errSummary: string = ''): WebError {
    return new WebError({isSuccess: true, errTitle, errSummary});
  }

  addField(fieldName: string, fieldError: string) {
    this.errFields.push({fieldName: fieldName, fieldError: fieldError});
  }
}

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

A guide to efficiently removing an element in Angular using TypeScript by considering certain properties

I need help removing an element from an array based on any property such as its key, name, or email. HTML <tr *ngFor="let person of persons;" (click)="remove(person.key)"> <td>{{person.key}}</td> <td>{{person.name}}</td> ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

Tips for managing your time while anticipating an observable that may or may not

I am facing a dilemma in my Angular app where I need to conditionally make an HTTP call to check for the existence of a user. Depending on the result of this call, I may need to either proceed with another API request or halt the processing altogether. I ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

Implementing Firebase-triggered Push Notifications

Right now, I am working on an app that is built using IONIC 2 and Firebase. In my app, there is a main collection and I am curious to know if it’s doable to send push notifications to all users whenever a new item is added to the Firebase collection. I ...

Display a loading indicator with the shortest possible delay whenever utilizing the React Router v6 Link functionality

Integrate React and Router v6 App.tsx: const Page1 = lazy(() => pMinDelay(import('./views/Page1'), 500)) const Page2 = lazy(() => pMinDelay(import('./views/Page2'), 500)) return ( <Suspense fallback={<Loading/>}gt ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

When using NextJS <Link, mobile users may need to tap twice to navigate

Whenever I use the NextJS <Link tag on my mobile device, I notice that I have to double-tap for the link to actually route to the desired page. Take a look at the code snippet below: <Link href="/methodology" passHref={true} ...

The ListItemButton's onclick event does not trigger on the initial click when utilizing a custom component as its children

I am having trouble comprehending why this onclick function is influenced by the children and how it operates <ListItemButton onClick={() => onClickResult(q)}> <Typography variant="body1">{highlighted}</Typography> ...

Exploring the power of NestJS integration with Mongoose and GridFS

I am exploring the functionality of using mongoose with NestJs. Currently, I am leveraging the package @nestjs/mongoose as outlined in the informative documentation. So far, it has been functioning properly when working with standard models. However, my p ...

Is it possible to eliminate the array from a property using TypeScript?

Presenting my current model: export interface SizeAndColors { size: string; color: string; }[]; In addition to the above, I also have another model where I require the SizeAndColors interface but without an array. export interface Cart { options: ...

The default value for the ReturnType<typeof setInterval> in both the browser and node environments

I have a question about setting the initial value for the intervalTimer in an Interval that I need to save. The type is ReturnType<typeof setInterval>. interface Data { intervalTimer: ReturnType<typeof setInterval> } var data : Data = { ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

Utilizing RavenDB with NodeJS to fetch associated documents and generate a nested outcome within a query

My index is returning data in the following format: Company_All { name : string; id : string; agentDocumentId : string } I am wondering if it's possible to load the related agent document and then construct a nested result using selectFie ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

Incorporating Google Pay functionality within Angular applications

I have been attempting to incorporate Google Pay into my Angular project, but I am struggling to find reliable resources. My main issue revolves around the following code... <script async src="https://pay.google.com/gp/p/js/pay.js" onloa ...

Creating a return type in TypeScript for a React Higher Order Component that is compatible with a

Currently utilizing React Native paired with TypeScript. Developed a HOC that functions as a decorator to add a badge to components: import React, { Component, ComponentClass, ReactNode } from "react"; import { Badge, BadgeProps } from "../Badge"; functi ...

Retrieve an enumeration from a value within an enumeration

In my coding project, I have an enum called Animals and I've been working on a function that should return the value as an enum if it is valid. enum Animals { WOLF = 'wolf', BADGER = 'badger', CAT = 'cat', } cons ...

What is the significance of having both nulls in vue's ref<HTMLButtonElement | null>(null)?

Can you explain the significance of these null values in a vue ref? const submitButton = ref<HTMLButtonElement | null>(null); ...

Is it possible for a function within a nodejs module to be defined but display as undefined upon access?

I am currently developing a Discord bot using NodeJS and TypeScript, and I'm facing an issue while trying to import custom modules in a loop with the following code: const eventFiles = fs.readdirSync("./src/events/").filter((file: string) =& ...