【问题标题】:Ts2532, Object is possibly 'undefined'Ts2532,对象可能是“未定义”
【发布时间】:2022-01-20 22:17:56
【问题描述】:

我正在尝试修补我正在使用平均堆栈创建的项目中的任务。所有 api 的工作,但是当我尝试使用 id 参数修补元素时,出现错误:

"Object is possibly 'undefined'".

我想做的是:

  1. 获取具有精确 id 的元素
  2. 使用该 id 作为查询来修补该元素

这是代码:

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

【问题讨论】:

    标签: javascript angular typescript mongodb mean-stack


    【解决方案1】:

    这个错误的原因是方程的正确值(右值)可能是undefined。避免此错误的一种方法是在将对象用作正确值之前检查对象是否为undefined。我了解在您的应用程序中,此错误是由 task.id 对象引起的。希望我们可以通过以下方式解决此问题:

    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 */
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用可选链接运算符 - ?:

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

      如果您确定task 的值不是nullundefined,您还可以使用非空断言运算符-!

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

      【讨论】:

      • const elId = task!.id,如果确定设置了id
      • 你是对的,它也可以使用。让我将其添加到答案中。
      • 这部分有效,但仍然显示:“对象”类型上不存在属性“id”
      • 是的,我没有将any 添加为类型。我更新了我的答案。你能再试一次吗?
      猜你喜欢
      • 2021-11-29
      • 2022-01-05
      • 2021-10-07
      • 2021-12-29
      • 2020-04-02
      • 2022-12-03
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多