GratefulDisciple
GratefulDisciple

Reputation: 704

How to mix static class factory method and instance method

When I add an instance method addField in the code below, the Typescript compiler produces an error for all my factory static method withError and withSuccess:

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 });
    }
}

What should I have done differently?

Upvotes: 1

Views: 86

Answers (1)

Collierre
Collierre

Reputation: 956

It's because withError() and withSuccess() return a WebError. addField() is a property of WebError, but the object your two static methods return does not include it. You could fix it by returning an actual WebError from the static methods, instead of just an object that satisfies its interface.

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});
  }
}

Upvotes: 1

Related Questions