网站搜索

typescript - 区分 FormData 中的条目 - 文件或字符串


我正在访问一个 FormData (链接) 值,该值是

type FormDataEntryValue = File | string;

.

有什么安全的方法来确定值是 File 还是 string?

答案显然不应包括 as、any 等

答案#1

使用缩小。

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