Alexander Kim
Alexander Kim

Reputation: 18401

FormData's types - TypeScript 3.5

Using FormData:

const formData = new FormData()
formData.append('document_title', this.document.document_title)
formData.append('file', this.document.file)
formData.append('document_language', this.document.document_language)

Document interface:

export interface IDocument {
  document_title: string
  file: File | null
  document_language: number
}

The error comes, when I try to formData.append not a String or blob, I'm getting an error:

Argument of type 'number' is not assignable to parameter of type 'string | Blob'.Vetur(2345)

and same with a file being null. I guess a FormData has its own interface in TS that accepts only string or blobs? How can I override this behavior?

Do not write about JSON.stringify().

Upvotes: 2

Views: 17813

Answers (2)

Stefano Belfiore
Stefano Belfiore

Reputation: 31

This is an interface for FormData body

export interface PostFileFormDataBody{
  [key: string]: string | Blob;
}

Upvotes: 0

Alexander Kim
Alexander Kim

Reputation: 18401

Solved using as any type assertion for compiler:

formData.append('document_title', this.document.document_title)
formData.append('file', this.document.file as any)
formData.append('document_language', this.document.document_language as any)

JSON.stringify() my number data feels wrong for me. On backend i transform formdata strings to intended types to store in db.

Upvotes: 2

Related Questions