Home > Mobile >  Ts2532, Object is possibly 'undefined'
Ts2532, Object is possibly 'undefined'

Time:12-18

I'm trying to patch a task in a project that I'm creating with the mean stack. All the api's work, but when I try to patch an element, with the id param, there's an error which says:

"Object is possibly 'undefined'".

What I want to do is:

  1. Get the element with a precise id
  2. Use that id as query to patch that element

This is the code:

    export class TaskServicesService {
        
      constructor(private myHttp: HttpClient) { }
    
      async updateTask(payload: any) : Promise<any> {
        const task = await this.myHttp.get('http://localhost:3000/').toPromise();
        const elId: any = task.id;
        return await this.myHttp.patch('http://localhost:3000/list/', {title: payload}).toPromise();
      }
    
    }

CodePudding user response:

The reason for this error is that the right value (rvalue) of the equation is probably undefined. One way to avoid this error is to check if an object is undefined before using it as a right value. I understand that in your application this error is caused by the task.id object. Hopefully we can fix this problem by:

if(task.id !== null && task.id !== undefined)
{
    const elId: task.id;
    return await this.myHttp.patch('http://localhost:3000/list/', {title: payload}).toPromise();
}
else
{
    /* Error Handling */
}

CodePudding user response:

Try using optional chaining operator - ?:

const task: any = await this.myHttp.get('http://localhost:3000/').toPromise();
const elId: any = task?.id;

If you are sure that task has value other than null or undefined, you can also use non-null assertion operator - !:

const task: any = await this.myHttp.get('http://localhost:3000/').toPromise();
const elId: any = task!.id;
  • Related