typescript 上传文件 formData声明的类型

const formData:any = new FormData();
const data = {
    name: 'admin',
    age: 18
}
for (const [key, value] of Object.entries(data)) {
    formData.append(key, value)
}
const fileList = this.fileList
if (fileList && fileList.length > 0) {
    for (const item of this.fileList) {
      formData.append('file', item.file)
    }
}

image.png

报错了

Argument of type 'string | LocationQueryValue[] | null' is not assignable to parameter of type 'string | Blob'.

请问怎么声明这个formData的类型?用any倒是也可以,但是既然用了typescript 就想知道怎么写

阅读 15.8k
2 个回答
const formData:any = new FormData();
const data = {
    name: 'admin',
    age: 18
}
for (const [key, value] of Object.entries(data)) {
    formData.append(key, value)
}
const fileList = this.fileList
if (fileList && fileList.length > 0) {
    for (const item of this.fileList) {
      formData.append('file', item.file as Blob)
    }
}

增加一个断言, item.file一定是Blob类型就行了

错误提示是说,你的value的类型不对。
value的类型应当是string或者Blob类型,而你的value可能是LocationQueryValue[]类型

推荐问题