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

What is the equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

How can we make type assertions consistent without sacrificing brevity?

In the project I am currently working on, we have implemented a warning for typescript-eslint/consistent-type-assertions with specific options set to { assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }. While I generally appr ...

What is the best way to assign a conditional value to this Angular attribute within my HTML code?

I'm currently developing a web application using Angular and PrimeNG. My question is whether it's possible to conditionally add a PrimeNG component attribute based on the value of a property. In my HTML file, I have the following code: <span [ ...

activating a component by interacting with another component

How can I pass the uuid from parent to child component through a click event in Angular? App.component.ts import { Component } from '@angular/core'; import { v4 as uuid } from 'uuid'; @Component({ selector: 'my-app', tem ...

A guide on utilizing NgFor for a standalone element

I am working with a component that interacts with a service to make REST calls. The code for the API service looks like this: api.service import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; i ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

Achieving TypeScript strictNullChecks compatibility with vanilla JavaScript functions that return undefined

In JavaScript, when an error occurs idiomatic JS code returns undefined. I converted this code to TypeScript and encountered a problem. function multiply(foo: number | undefined){ if (typeof foo !== "number"){ return; }; return 5 * foo; } ...

What are the best strategies for managing npm dependencies alongside other packages?

I am working on an Angular app that has the following dependencies: "dependencies": { "personalUiLibrary": "1.0.0" }, "devDependencies": { "tailwindcss": "^2.2.7" } In the personalUiLibrary p ...

Is it time to end my MediaObserver subscription in flex-layout for Angular?

Within my Angular component, I have implemented the following code to display different elements based on screen resolution: constructor(private mediaObserver: MediaObserver) {} private mySubscription: Subscription; public ngOnInit(): void { this.my ...

Include a tab button within a vertical tab list using Angular Material

I have utilized Angular Material to create a vertical tab, and I would like to incorporate an Add Tab button within the tab listing itself. Currently, when I add the button, it appears at the bottom of the layout instead. For reference, you can access the ...

In TypeScript, how are angle brackets like methodName<string>() utilized?

Could someone please assist me in understanding why we use angular brackets <> in typescript? For example, I have provided some code below and would appreciate an explanation. export class HomePage { constructor(public navCtrl: NavController) ...

Navigating to native script, the method for extracting an ID from a link is revealed

Is there a way to extract the unique identifier from this URL: I want to retrieve the code "11E89887FABBC1D" when clicking on the link. Any suggestions? ...

Is there a way to retrieve the value of bindings in the component controller using Angular 1.5 and Typescript?

In my quest to develop a versatile left-hand menu component that can dynamically display different menu structures based on input strings, I stumbled upon an interesting challenge. By binding a string to the <left-hand-menu-component> element like so ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

Problem with authorization on Cloud run

I successfully deployed both the backend and frontend to Google Cloud Run. The frontend is built with Angular 16 using server-side rendering (SSR). On the backend, I have a Node.js application running Express. Since I am utilizing SSR, requests should o ...

How can I implement password autofill feature on iOS using Ionic 4 and Capacitor?

I recently developed an app on the Apple Store using Ionic 4 & Capacitor. However, I am facing issues with saving the ID and password during the first login and updating it later. I have tried: Adding an Associated Domain file to the domain (https://dev ...

Error message: When attempting to redirect to another route, there is a type error with 'this' as it is implicitly assigned the type 'any'

I'm facing an issue with a component I've built using hooks. I want it to redirect to a different route when a function is called and the server response is received. However, my TypeScript is throwing an error: Type error: 'this' impl ...

What is the best way to create a case-insensitive sorting key in ag-grid?

While working with grids, I've noticed that the sorting is case-sensitive. Is there a way to change this behavior? Here's a snippet of my code: columnDefs = [ { headerName: 'Id', field: 'id', sort: 'asc', sortabl ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...