在TypeScript中定义FileList和File类型的对象时遇到了问题。

huangapple go评论77阅读模式
英文:

Having trouble defining an object of type FileList and File in Typescript

问题

以下是翻译好的部分:

我有一个要提交到API的表单,其中包含一个类型为 FileList 的图像。

FileList 中的第一个图像在 image[0] 处,类型为 File,如下所示:

在TypeScript中定义FileList和File类型的对象时遇到了问题。

因此,我的API接收到上述类型为 File 的图像,我试图设置我的表单类型,以便它获得适当的图像类型。

这是我的表单类型的样子:

type FormValues = {
  ...
  image: string | File;
};

我想从这个对象中提取只有 name 属性。我还希望图像可以是 stringFile 类型。当我尝试提取 form.image.name 这样的 name 属性时,我会得到以下错误:

Property 'name' does not exist on type 'string | File'.
Property 'name' does not exist on type 'string'.ts(2339)

我无法定义一个带有 name 属性的 File 类型的对象。我明白我需要做什么,但似乎无法解决问题。

英文:

I have a form to submit to an API that has an image of type FileList.

The first image in FileList at image[0] of type File looks like this:

在TypeScript中定义FileList和File类型的对象时遇到了问题。

So my API receives an image of File type above and I'm trying to set my Form type so it gets a proper image type.
This is what my form's type looks like:

type FormValues = {
  ...
  image: string | File;
};

I want to extract only the name property from this object. I also want image to either be a string or a File type. As I'm trying to extract a name property such as form.image.name I get a following error:

Property 'name' does not exist on type 'string | File'.
Property 'name' does not exist on type 'string'.ts(2339)

I've failed at defining an object of type File with a name property in it. I understand what I have to do, but can't seem to figure it out.

答案1

得分: 2

你需要在这里使用type narrowing,特别是类型保护。

type FormValues = {
  // ...
  image: string | File;
};

function isFile(value: string | File): value is File {
  return value instanceof File;
}

const form: FormValues = {
  // ...
  image: new File(["file contents"], "example.jpg", { type: "image/jpeg" }),
};

if (isFile(form.image)) {
  console.log("图片名称:", form.image.name);
} else {
  console.log("图片:", form.image);
}

如果您确信在特定情况下图像是一个文件,您还可以使用as类型断言,但我认为这会破坏类型检查的目的。

英文:

You need to use type narrowing, type guards in particular here.

type FormValues = {
  // ...
  image: string | File;
};

function isFile(value: string | File): value is File {
  return value instanceof File;
}

const form: FormValues = {
  // ...
  image: new File(["file contents"], "example.jpg", { type: "image/jpeg" }),
};

if (isFile(form.image)) {
  console.log("Image name:", form.image.name);
} else {
  console.log("Image:", form.image);
}

You can also use as type assertion if you're sure that the image is a File in that specific case, however that defeats the purpose of typechecking imo.

huangapple
  • 本文由 发表于 2023年6月16日 13:34:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487213.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定