Tips for fixing TypeScript compiler error TS2339: Issue with accessing 'errorValue' property in Angular 5 project

Within a component, I have developed a function to manage errors returned from a Rest Service and determine the corresponding error message to display to the user. This method accepts an error object (custom data structure from the service), navigates to extract the relevant information, and then uses a switch statement to pass a JSON key for translation via an i18n service, as shown below:

private myErrorHandler(err: any): string {
    // Why doesn't typescript support null-conditional?
    if (err.error && err.error.errors && err.error.errors[0] && err.error.errors[0].error) {
      const errorMsg = err.error.errors[0].error;
      const errorValue = err.error.errors[0].value;
      const translationArgs: any = { errorValue: null };
      let correctMsg;

      if (errorValue) {
        translationArgs.errorValue = errorValue; 
      }

      switch (errorMsg) {
        case 'not_unique': {
          correctMsg = errorValue ? 'common.validation.not_unique_value' : 'common.validation.not_unique';
          break;
        }
        default: {
          correctMsg = 'common.messages.global_error';
          break;
        }
      }
      return this.localizationService.translate(correctMsg, translationArgs as any);
    }
    return this.localizationService.translate('common.messages.global_error');
  }

However, I face an issue when attempting to include some of the error data in the returned message as an argument. The code snippet below raises a TypeScript compiler error:

if (errorValue) {
            translationArgs.errorValue = errorValue;
}

I seek guidance on how to resolve this linting error. I initially assumed that assigning a null value to the errorValue property in the translationArgs object would suffice, but it seems I was mistaken. Any suggestions will be highly appreciated.

I acknowledge that the method/function may not be structured optimally, so any feedback on this aspect is also welcome.

Below you can find the contents of my tsconfig file for reference:

{
  "compilerOptions": {
    "alwaysStrict": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es6",
      "dom"
    ],
    "module": "commonjs",
    "moduleResolution": "node",
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "outDir": "dist",
    "pretty": true,
    "sourceRoot": "frontend",
    "rootDir": "frontend",
    "sourceMap": true,
    "target": "es5",
    "types": [
      "node",
      "mocha",
      "chai",
      "chai-as-promised",
      "aws-sdk",
      "q",
      "sinon",
      "file-saver"
    ],
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "include": [
    "frontend/**/*.ts"
  ],
  "exclude": [
    ".git",
    ".idea",
    "config",
    "dist",
    "e2e_tests",
    "gulp",
    "node_modules",
    "reports",
    "server",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "useWebpackText": true
  },
  "angularCompilerOptions": {
    "debug": false
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

Answer №1

I have successfully implemented your tslint configuration without encountering any issues. Below is a slightly optimized version of the code.

myErrorHandler(err: any): string {

  let error: any;
  try {
    error = err.error.errors[0];
  } catch (e) {
    return this.localizationService.translate('common.messages.global_error');
  }

  const errorMsg = error.error;
  const errorValue = error.value;
  const translationArgs = {errorValue: null};
  let correctMsg;

  if (errorValue) {
    translationArgs.errorValue = errorValue;
  }

  switch (errorMsg) {
    case 'not_unique': {
      correctMsg = errorValue ? 'common.validation.not_unique_value' : 'common.validation.not_unique';
      break;
    }
    default: {
      correctMsg = 'common.messages.global_error';
      break;
    }
  }
  return this.localizationService.translate(correctMsg, translationArgs as any);

}

Answer №2

While not the most elegant approach, a viable option is to implement

(translationArgs as any).errorValue = errorValue;

Alternatively, consider specifying a more suitable type instead of using any or an empty object like {}.

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

Convert a regular element into a DebugElement within an Angular framework

Recently, I was working on testing an Angular Component which was going smoothly until I encountered a challenging issue that has been perplexing me for days. My main objective was to test whether the method "ajouterCompteurALaCampagne" is being called whe ...

Finding it challenging to adapt an AngularJs component-based modal to TypeScript

When creating an AngularJS component in JavaScript and displaying it as a modal using ui-bootstrap, you need to pass bindings that the modal instance can use for dismissing or closing itself: app.component("fringeEdit", { controller: "FringeEditCont ...

What method can be used to verify if a username exists within Angular data?

We want to display online users on a webpage by checking if they are currently active. The current code logs all online users in the console, but we need to show this visually on the page. public isOnline: boolean = false; ... ... ngOnInit() { ...

Error encountered while upgrading to Angular 5: splitHash issue

Currently in the process of transitioning from Angular 4.x to 5.x, I have encountered the following error: main.81bcdf404dc22078865d.bundle.js:1 Uncaught TypeError: i.splitHash is not a function at Object.t.parseUrl (main.81bcdf404dc22078865d.bundle.js:1) ...

What could be the reason behind the for loop not running within a typescript function?

My confusion lies in the for loop within this function that seems to never run. Each console log is set up to return a specific value, but the looping action doesn't trigger. Can someone provide insight into what might be causing this issue? export fu ...

Is there a way to invoke a function within a mat-error element?

I need to display an error message in my input field! The function will return true if both passwords match, otherwise it will return false. How can I invoke a boolean function inside mat-error! My Function: checkPasswords(): Boolean { // 'passwords& ...

What is the best way to merge two approaches for tallying items within each category?

I have an Angular 8 application that includes two methods for displaying the number of items in each category. These items are retrieved from the back-end and are categorized as follows: <mat-tab> <ng-template mat-tab-label> ...

"Encountering an unexpected error when Dockerizing an Angular App on Win10 Professional: EXPAND-ARCHIVE instruction not

I need to create a docker image for an Angular web application and deploy it on a Windows machine. However, I'm running into an issue when executing the command: docker build -t node . The following exception is thrown: Error response from daemon: ...

TS2322 error: What does it mean when the type is both not assignable and assignable?

I've been delving into the world of generics with Java and C#, but TypeScript is throwing me for a loop. Can someone shed some light on this confusion? constructor FooAdapter(): FooAdapter Type 'FooAdapter' is not assignable to type 'A ...

Conceal the menu in Angular Material when the mouse leaves the button

When the mouse hovers over a button, a menu is displayed on the website's toolbar. The menu is set to close when the mouse leaves a surrounding span element. Now, there is an attempt to also close the menu when the mouse leaves the triggering button i ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...

Exploring the Features of Angular 6 through Interface Properties

Is there a way to add a description attribute to a property, similar to the data descriptions in dot net? For example: interface ModuleStatus { [Description "Module state"] moduleStateSymbol: string; [Description "Module type"] moduleTypeS ...

I'm experiencing unexpected behavior with the use of Mat-Spinner combined with async in Angular 12, particularly when using the rxjs function

I am relatively new to rxjs and it's possible that I'm using the wrong function altogether. Currently, I'm working on a .NET Core 3.1 backend and implementing a two-second delay for testing purposes. I have a service call that I need to mock ...

Inform the PHP backend that the browser has been closed by the frontend Angular application

Currently, I am working on an Angular project that is interacting with a backend project created using PHP and ZF3. I am trying to figure out the most efficient method of informing the backend project when the user closes the browser window. Initially, I ...

What are the different types of class properties in TypeScript?

Currently, I am incorporating ES6 classes in typescript using the following code snippet: class Camera { constructor(ip) { this.ip = ip; } } Despite encountering an error message, it appears that the code still compiles successfully. The ...

Exploring disparities between the Client SDK and Admin SDK in conducting firestore queries

I am encountering difficulties with my query while running it in Firebase Functions. It functions perfectly on the client side, but fails to work in Functions. I am curious if there is a way to modify it to function with Admin SDK as well. Am I making any ...

Adding External Libraries to Angular-CLI: Expanding Your Toolkit with jQuery and Bootstrap

Right now I have to: Install local libraries using npm install bootstrap and npm install jquery Create a folder called src\assets Copy all files from node_modules/bootstrap and node_modules/jquery In index.html <script src="assets/jquery/jquery ...

Step-by-step guide on setting up a personalized validation using Formly alongside a calendar input

I have successfully implemented a custom calendar template, but I am struggling with creating validators and error messages. Most examples I found online deal with input elements, whereas my element is not an input. app.modules.ts FormlyModule.forRoot({ e ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...