[英]Ts2532, Object is possibly 'undefined'
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:所有 api 的工作,但是当我尝试使用 id 参数修补一个元素时,出现一个错误,上面写着:
"Object is possibly 'undefined'".
What I want to do is:我想做的是:
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();
}
}
The reason for this error is that the right value (rvalue) of the equation is probably undefined
.这个错误的原因是方程的正确值(右值)可能是undefined
。 One way to avoid this error is to check if an object is undefined
before using it as a right value.避免此错误的一种方法是在将 object 用作正确值之前检查它是否undefined
。 I understand that in your application this error is caused by the task.id
object.我了解在您的应用程序中,此错误是由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 */
}
Try using optional chaining operator - ?
尝试使用可选链接运算符 - ?
: :
const elId = task?.id;
If you are sure that task
has value other than null or undefined , you can also use non-null assertion operator - !
如果您确定该task
的值不是null或undefined ,您还可以使用非空断言运算符 - !
: :
const elId = task!.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.