Search code examples
typescriptform-data

Distinguish Entry in FormData - File or string


I am accessing a FormData (LINK) value which is of

type FormDataEntryValue = File | string;

.

What is a safe method to determine whether the value is a File or string?

Answer should obviously not include as, any, ..


Solution

  • Use narrowing.

    const val: FormDataEntryValue = ...
    if (typeof val === 'string') {
      // type is inferred to be a string
    } else {
      // type is inferred to be a File
    }