Typescript: Property 'name' does not exist on type 'FormDataEntryValue'
Asked Answered
M

4

9

I have:

const file = formData.get('documents[]')

What type is file?

const file: FormDataEntryValue | null

I need to access to file?.name.

and i got:

Property 'name' does not exist on type 'FormDataEntryValue'.

Mort answered 12/2, 2022 at 10:21 Comment(1)
If file is null, how do you expect to get the name property of it? Also, FormDataEntryValue is defined as either a string or a File. A string does not have a name property.Waldner
P
18

FormDataEntryValue is defined as an union of File and string: type FormDataEntryValue = File | string;

Thus you need to check first that the variable is indeed a File:

if (file instanceof File) {
  console.log(file.name);
}
Psychotic answered 14/2, 2022 at 13:23 Comment(1)
Where does type FormDataEntryValue come from? It's built in to TS?Dr
A
8

FormData.get() returns a value of type string | File | null.

If you know that it is going to be a file, use:

const file = formData.get('documents[]') as File

Here is a reference, https://dev.to/deciduously/formdata-in-typescript-24cl

Amherst answered 5/5, 2023 at 13:57 Comment(0)
T
2

I've got the similar issue for string property 'toUpperCase' does not exist on type 'FormDataEntryValue'. This is how I resolve my issue:

const name = (data.get("name") as string).toUpperCase();

So the explanation is that, data.get() returns FormDataEntryValue | null so I simply change/refer the type as string then apply the upper case function.

Terhune answered 15/5 at 21:50 Comment(0)
V
1

Property 'name' does not exist on type 'FormDataEntryValue'.

As error says, looks like key passed in the FormData.get() or the name property in file variable doesn't exist.

The get() method of the FormData interface always returns the first value associated with a given key from within a FormData object.

Hence, As per your code. Looks like documents is an array of object. Hence, you can access the name by file[0]?.name instead of file?.name

formData.append('documents', '[{name: "alpha"}]');

const file = formData.get('documents')

const fileName = file[0]?.name // returns alpha
Valvate answered 15/2, 2022 at 5:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.