Setting an optional property to null is not permitted

In my model class, I have defined an optional property as follows:

export class Workflow {
  constructor(
    public id: number,
    public started: Date,
    public documentId: number,
    public document: Document,
    public status: WorkflowStatus,
    public workflowEvents: WorkflowEvent[],
    public startingUserId: number,
    public statusValue?: string,
  ) {}
}

I also have a pipe that converts the status property to a string:

import { Pipe, PipeTransform } from '@angular/core';
import { WorkflowStatus } from '../models/workflowstatus.enum';

@Pipe({ name: "status" })
export class WorkflowStatusPipe implements PipeTransform {
  public transform(value: WorkflowStatus): string {
    switch (value) {
      case WorkflowStatus.ForwardedToApprover: return "TOV";
      case WorkflowStatus.ReadedByApprover: return "OLV";
      case WorkflowStatus.Commented: return "MEGJ";
      case WorkflowStatus.Approved: return "JÓV";
      case WorkflowStatus.ForwardedToManager: return "MAN";
    }
  }
}

Next, there are document objects with workflows. The documents are fetched via an API call:

    this.documentRepo.getDocuments().subscribe(documents => {
      documents.forEach(function (document) {
        document.workflow.statusValue = new WorkflowStatusPipe().transform(document.workflow?.status);
      });
      this.documents = documents;
    });

However, attempting to transform the status value to a string generates an error in the console: 'Cannot set property 'statusValue' of null'.

This is perplexing since the statusValue property is marked as optional.

What modifications should be made to the code?

EDIT:

This is an example of a document object retrieved from getDocuments:

https://i.sstatic.net/F3JW1.png

Also worth mentioning, assigning a random string to statusValue triggers the same error:

    this.documentRepo.getDocuments().subscribe(documents => {
      documents.forEach(function (document) {
        document.workflow.statusValue = "x";//new WorkflowStatusPipe().transform(document.workflow?.status);
      });
      this.documents = documents;
    });

Answer №1

To handle the scenario where the property document.workflow is either non-existent or null, you can set a default workflow value for documents without a workflow. Here is an example of how you could approach this:

this.documentRepository.fetchDocuments().subscribe(docs => {
  docs.forEach(function (doc) {
    if (doc.workflow) {
      doc.workflow['statusValue'] = new WorkflowStatusConverter().transform(doc.workflow?.status);
    }
  });
  this.documentsList = docs;
});

It's important to also consider that if document.workflow.status does not align with any cases in your switch statement, it will return as undefined. Depending on your requirements, you may want to incorporate a default case to handle such scenarios.

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

Angular 2: Implementing service functions on button click using the (click) event

Is it possible to call a function from my service when clicking on an element in the HTML returned from an HTTP call? Here is the HTML snippet: <a (click)="SellingVarietiesService.goToVarietyDetails(3)">Test</a> The function I want to call i ...

Automate your builds with Github actions for both tags and branches!

In my typescript project repository, our release policy states that we publish packages from the master branch to the next npm tag. Additionally, we have a dedicated branch called release for publishing to the latest npm tag. My goal is to optimize the sol ...

Attempting a second filter of the table using the dropdown results in no data being returned

I've developed a CRUD app using Angular 7, and I'm facing an issue. When I select a dropdown item for the first time, it shows the desired table data. However, on selecting another item for the second time, it returns nothing. Below is my compone ...

"Incorporating the node_modules folder into the Express.js compilation process

Is there a way to automatically include dependencies during Express.js compilation, similar to building a React project? I want to avoid dealing with dependencies after the build process. Any suggestions on how to achieve this? I have not attempted any so ...

Adapting the current codebase to be compatible with Typescript

Currently, my codebase is built with redux, redux-saga, and react using plain Javascript. We are now considering incorporating Typescript into the project. Some questions arise: Can plain Javascript files coexist with tsx code? I believe it's possibl ...

What is the best way to execute a function from a parent element within the child element?

Currently, I am working with two components - Navbar (parent) and Setting Menu (Child). const Navbar: React.FC = () => { const classes = useStyles(); const [randomState, setrandomState] = useState(false); const randomStateFunction = () =>{ ...

Error encountered in Jest when trying to use next/font/local: TypeError - (0, _local.default) is not a function

Currently, I am in the process of developing a UI library utilizing MUI, React, and TypeScript within Nx as the build system. To ensure smooth functionality, Jest is being used for testing purposes. However, I recently encountered an issue while attempting ...

The most efficient method for receiving real-time updates from the server to the app is through Angular 7

Currently, I am in the process of developing an Angular 7 messages service (user to user) for my website. The approach I have taken involves receiving updates from the server (Yii2 REST API) every 3 minutes using an interval function (see code snippet belo ...

Need help in NestJS with returning a buffer to a streamable file? I encountered an error stating that a string is not assignable to a buffer parameter. Can anyone provide guidance on resolving this issue?

The issue description: I am having trouble returning a StreamableFile from a buffer. I have attempted to use buffer.from, but it does not seem to work, resulting in the error message below. Concern in French language: Aucune surcharge ne correspond à cet ...

What is the correct way to assign multiple types to a single entity in TypeScript?

(code at the end) While attempting to write section.full.link, I encountered the following error: Property 'link' does not exist on type 'SectionSingle | SectionTitle | SectionHeaderMedia'. Property 'link' does not exist on ...

Adjust property value based on changes in a related property

Currently, I am developing a TypeScript-powered Angular (5) application and I have encountered a puzzling question that is proving elusive to solve. Let me illustrate with the following example: ... export class SomeComponent implements onInit { ... ...

Initiate npm start with CORS enabled

Currently, I am developing a small application using Angular2. Following the instructions provided in the 5min. Quickstart Guide, I used npm to install necessary modules and initiate a lite-server. However, my ultimate goal is to integrate this app into ...

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) ...

Avoiding repeated observable executions

My current task involves implementing a screen that displays constantly changing data from an API. To achieve this, I have utilized the repeatWhen() method on the observable generated by the API call for polling purposes. Additionally, I need to make an ex ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

What is the process for removing a particular file from my bundle?

I am currently utilizing webpack to build my angular2/typescript application and have successfully generated two files, one for my code and another for vendors. However, I am in need of a third file to separate my config (specifically for API_ENDPOINT) whi ...

What could be causing Typescript Intellisense to not display Object extensions?

Let's take a look at this unique way to extend the Object type: interface Object { doSomething() : void; } Object.prototype.doSomething = function () { //perform some action here } With this modification, both of the following lines will c ...

Troubleshooting CORS Problem in Angular 8 and Java Spring Framework

I've been struggling with a major issue for hours now. I am developing an Angular app that communicates with a Java Spring API. All of my POST/GET/DELETE requests are working fine, except for one: the POST request to "/login", which requires sending d ...

How to conceal an element in Angular using its unique identifier

I am looking for a way to toggle the visibility of an element based on its ID. I have a dynamic list with the following structure in my TS component: vehicles = [ { "id": 1, "type": "car", ...

Customize the color of the Material-UI Rating Component according to its value

Objective I want to dynamically change the color of individual star icons in a Ratings component (from material-ui) based on the value selected or hovered over. For example, hovering over the 1st star would turn it red, and hovering over the 5th star woul ...