TypeScript中HttpEvent.total提示未定义,无法计算上传进度百分比
解决上传进度计算中
event.total的TypeScript类型报错问题 问题说明
上传文件时,尝试通过event.loaded / event.total计算上传进度百分比,但TypeScript抛出object is possibly 'undefined'错误,尽管控制台输出里total有明确数值。
控制台输出示例
Object { type: 1, loaded: 1048105, total: 1334347 } loaded: 1048105 total: 1334347 type: 1 <prototype>: Object { … } app.component.ts:84:20 Object { type: 1, loaded: 1128059, total: 1334347 } app.component.ts:84:20 Object { type: 1, loaded: 1227405, total: 1334347 } app.component.ts:84:20 Object { type: 1, loaded: 1334347, total: 1334347 }
出错代码片段
onuploadFile( files : File[]): void{ console.log(files) const formData = new FormData() for(const file of files){ formData.append('files', file, file.name) } this.user.uploadFiles(formData).subscribe({ next: (event) => { switch(event.type){ case HttpEventType.UploadProgress || HttpEventType.DownloadProgress: console.log(event) this.filestatus.percentage = Math.round( 100 * event.loaded / event.total) // 此处报错:object is possibly 'undefined' this.filestatus.status = 'progress' break; case HttpEventType.Response: console.log(event) this.filestatus.percentage = 0 this.filestatus.status = 'done' break; } }, error: (e) => console.log(e), complete: () => console.log('done uploading') }) }
解决方案
1. 非空断言(快速解决,适用于确定total必存在的场景)
用!告诉TypeScriptevent.total不会是undefined,直接跳过类型检查:
this.filestatus.percentage = Math.round(100 * event.loaded / event.total!)
2. 空值合并+默认值(更安全,避免极端情况)
如果担心total可能为undefined,用??设置默认值,防止出现除以0的报错:
this.filestatus.percentage = Math.round(100 * event.loaded / (event.total ?? 1))
3. 类型守卫(严谨写法,明确处理两种情况)
通过判断total是否存在,让TypeScript自动缩小类型范围,同时处理异常场景:
if (event.total !== undefined) { this.filestatus.percentage = Math.round(100 * event.loaded / event.total) } else { // 可选:处理total不存在的情况,比如设为0或提示用户 this.filestatus.percentage = 0 }
额外修正:switch case的逻辑错误
原代码中case HttpEventType.UploadProgress || HttpEventType.DownloadProgress:的写法无效,||会返回第一个真值,导致只有UploadProgress会被匹配。正确写法是拆分两个case:
switch(event.type){ case HttpEventType.UploadProgress: case HttpEventType.DownloadProgress: console.log(event) // 进度计算逻辑 this.filestatus.status = 'progress' break; case HttpEventType.Response: // 完成逻辑 break; }
内容的提问来源于stack exchange,提问作者Sen Kanna
相关产品推荐
相关产品推荐

