[英]TypeScript asking to add type to key value
I've got form in my angular project.我的 angular 项目中有表格。 And this form contains input with image upload.
此表单包含带有图像上传的输入。 So I use FormData to send the data to server.
所以我使用 FormData 将数据发送到服务器。 I try to use function to append form fields to FormData.
我尝试使用 function 到 append 表单字段到 FormData。
export function toFormData<T>(formValue: T) {
const formData = new FormData();
for (const key of Object.keys(formValue)) {
const value = formValue[key]; <--- error here
formData.append(key, value);
}
return formData;
}
sendForm() {
const team = toFormData(this.form.value);
this.teamService.sendTeam(team).subscribe(() => {});
}
I've got an error from ts-lint "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. No index signature with a parameter of type 'string' was found on type 'unknown'".我从 ts-lint 得到一个错误“元素隐含地有一个‘任何’类型,因为‘字符串’类型的表达式不能用于索引类型‘未知’。没有带有‘字符串’类型参数的索引签名是在“未知”类型上找到”。 IDE underlines formValue[key] expression.
IDE 下划线 formValue[key] 表达式。 Try to add types, but it didn't help.
尝试添加类型,但没有帮助。
formValue[key]
is any
because T
doesn't narrow types, that's fine. formValue[key]
是any
因为T
不会缩小类型,这很好。
To suppress this error you need to cast any
to unknown
like that T extends Record<string, unknown>
.要抑制此错误,您需要将
any
转换为unknown
,例如T extends Record<string, unknown>
。 Now it means value
has unknown type and it should be asserted first before usage of the variable.现在它意味着
value
具有未知类型,并且应该在使用变量之前首先声明它。
export function toFormData<T extends Record<string, unknown>>(formValue: T) {
const formData = new FormData();
for (const key of Object.keys(formValue)) {
const value = formValue[key];
// feel free to remove Blob if it's not your case.
if (typeof value !== 'string' && !(value instanceof Blob)) {
continue;
}
formData.append(key, value);
}
return formData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.